mybatis的mapper动态代理、解决属性名和字段名不一致

2022-08-13 13:48:56

mybatis的mapper动态代理:

  1、在mybatis.xml中的mappers标签配置mapper.xml包的路径 注意是mappers标签下的package标签才配置mapper.xml包的路径
  (1.1)如果是mappers标签下的mapper标签则配置mapper.xml的路径
  2、在mapper.xml中的mapper标签的namespace属性配置mapper包下的dao文件名不加文件类型
  (2.1)对应1.1 如果是mapper标签的namespace属性配置dao包下的dao文件名不加文件类型

mybatis.xml代码:

<?xml version="1.0" encoding="UTF-8"?><!-- 引入约束(引入这个东西后,这个配置文件则有了一些提示标签,并且有一些语法校验) --><!-- 提示alt+/ --><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- configuration中的字标签是有顺序的,不能颠倒 --><!-- 设置配置文件位置 --><propertiesresource="com/zx/mybatis/properties/jdbc.properties"></properties><settings><!-- mybatis整合log4j  1.x 版本就这么写 --><settingname="logImpl"value="LOG4J"/></settings><!-- 用来配置mybatis别名 --><typeAliases><!-- package指定的包下所有的类都可以直接用类名表示,而不需要再写全路径 --><packagename="com.zx.mybatis.entity"/><!-- 二选一,不能同时存在 --><!-- <typeAlias type="com.zx.mybatis.entity.Student" alias="stu" /> --></typeAliases><!-- 用来配置环境的(连接参数) --><environmentsdefault="zy"><environmentid="zy"><!-- 将事务交由jdbc管理 --><transactionManagertype="JDBC"></transactionManager><dataSourcetype="POOLED"><!-- ${}语法是从.properties配置文件中获取对应值 --><propertyname="driver"value="${jdbc.driver}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/></dataSource></environment></environments><!-- 配置映射xml配置文件路径 --><mappers><!-- resource:用来配置相对路径xml文件 url:用来配置绝对路径xml文件 class:用来配置类路径 --><!-- <mapper resource="com/zx/mybatis/mapper/StudentMapper.xml" /> --><!-- package配置多个(类路径) --><!-- 只能找到接口路径,但接口和xml的关系无法关联 --><!-- 
			如果想使用package标签配置一个包下的所有xml文件要满足以下条件:
			1.dao接口和mapper.xml名称必须一致
			2.dao接口和mapper.xml必须放在同一路径下
		 --><packagename="com.zx.mybatis.mapper"/></mappers></configuration>

log4j.properties代码:

##DEBUG代表日志输出级别,stdout我们起的一个别名
log4j.rootLogger=DEBUG, stdout##这是我们日志输出需要用到的类
log4j.appender.stdout = org.apache.log4j.ConsoleAppender##输出的目录:System.out表示输出到控制台
log4j.appender.stdout.Target = System.out##格式化用到的工具类
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout##以如下格式输出
log4j.appender.stdout.layout.ConversionPattern=%d[%t] %-5p %c- %m%n

注意:
  mybatis.xml中mappers标签下想用package标签,mapper.xml和dao必须在同一个包下且文件命名的名字必须相同

dao接口代码:

packagecom.zx.mybatis.mapper;importcom.zx.mybatis.entity.Student;publicinterfaceStudentMapper{/**
	 * 保存用户
	 * @param stu
	 * @return
	 */publicintsaveStudent(Student stu);/**
	 *查询用户
	 * @param id
	 * @return
	 */publicStudentselectStu(int id);}

mapper代码:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- mapper.xml的父标签 namespace+id==类名+方法名 --><!-- 
		如果想让接口和xml关联,必须满足如下配置:
			1.namespace的值是接口的全路径
			2.xml中标签的id必须关联dao接口中的方法名
	--><mappernamespace="com.zx.mybatis.mapper.StudentMapper"><insertid="saveStudent"parameterType="Student"><!-- 注意:sql结尾不要加分号 -->
		insert into STUDENT (ID,USER_NAME,AGE,SCORE) values (#{id}, #{name}, #{age}, #{score})</insert><!-- 
		parameterType:参数类型
		resultType:返回值类型
	 --><selectid="selectStu"parameterType="_int"resultType="Student"><!-- 注意:sql结尾不要加分号 --><!-- 当只有一个参数时,参数名可以任意写 -->
		select id, name, age, score from student where id = #{iidd}</select><updateid="gxStudent"parameterType="Student">
		update student set name=#{name}, age=#{age}, score=#{score} where id=#{id}</update><deleteid="scStudent"parameterType="_int">
		delete from student where id=#{id}</delete><!-- 查所有List,resultType中的返回值类型写List中的泛型 --><selectid="selectListStudent"resultType="Student">
		select id, name, age, score from student</select><!-- 查所有Map,resultType中的返回值类型写Map中value的泛型 --><selectid="selectMapStudent"resultType="Student">
		select id, name, age, score from student</select><!-- 查所有Map,resultType中的返回值类型写Map中value的泛型 --><!-- 模糊查询,写死字符串传参时只识别${}的语法 --><selectid="mhSelectStudent"parameterType="string"resultMap="myStudent"><!-- select * from student where name like '${abc}%' --><!-- 模糊查询,动态传参时可识别#{}的语法,防止sql注入 --><!-- #{}是占位,${}是拼接 --><!-- 如果属性名和字段名不一致,解决方法1:在sql中给字段起别名 -->
		select id, user_name, age, score from student where user_name like concat(#{abc}, '%')<!-- 如果属性名和字段名不一致,解决方法2:使用resultMap进行映射 --></select><!-- 自定义结果集映射 --><resultMapid="myStudent"type="Student"><!-- 主键的映射关系,column:字段名,property:属性名 --><idcolumn="id"property="id"/><!-- 非主键关系映射用result --><resultcolumn="user_name"property="name"/><resultcolumn="age"property="age"/><resultcolumn="score"property="score"/></resultMap></mapper>

java实体类代码:

packagecom.zx.mybatis.entity;/**
 * 学生类
 * @author zhangyi
 *
 */publicclassStudent{privateint id;privateString name;privateint age;privatedouble score;publicStudent(){super();}publicStudent(int id,String name,int age,double score){super();this.id= id;this.name= name;this.age= age;this.score= score;}publicintgetId(){return id;}publicvoidsetId(int id){this.id= id;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name= name;}publicintgetAge(){return age;}publicvoidsetAge(int age){this.age= age;}publicdoublegetScore(){return score;}publicvoidsetScore(double score){this.score= score;}@OverridepublicStringtoString(){return"Student [id="+ id+", name="+ name+", age="+ age+", score="+ score+"]";};}

jdbc.properties代码:

jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=duay
jdbc.password=123456

java测试代码:

packagecom.zx.mybatis.test;importjava.io.IOException;importjava.io.InputStream;importjava.util.List;importjava.util.Map;importjava.util.Set;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importorg.junit.Test;importcom.zx.mybatis.entity.Student;importcom.zx.mybatis.mapper.StudentMapper;importcom.zx.mybatis.util.MybatisUtil;publicclassTest1{@TestpublicvoidTest01(){//主配置文件的位置String resource="mybatis.xml";//加载对应路径下的配置文件到流中InputStream inputStream=null;try{
			inputStream=Resources.getResourceAsStream(resource);}catch(IOException e){
			e.printStackTrace();}//sqlSession工厂:用来创建sqlSessionSqlSessionFactory sqlSessionFactory=newSqlSessionFactoryBuilder().build(inputStream);//创建sqlSessionSqlSession sqlSession= sqlSessionFactory.openSession();/*
		 * 调用sqlSession的新增方法
		 * statement:mapper.xml的位置(namespace+id)
		 * parameter:参数
		 * result:这条sql影响的条目数
		 */int result= sqlSession.insert("a.b.c.xzStudent",newStudent(11,"李四",23,90.01));//提交
		sqlSession.commit();System.out.println(result);//释放资源
		sqlSession.close();}@TestpublicvoidTest02(){SqlSession sqlSession=MybatisUtil.getSqlSession();Student stu= sqlSession.selectOne("a.b.c.cxStudent",1);System.out.println(stu);
		sqlSession.close();}@TestpublicvoidTest03(){//updateSqlSession sqlSession=MybatisUtil.getSqlSession();int result= sqlSession.update("a.b.c.gxStudent",newStudent(11,"李四123",23,90.01));System.out.println(result);
		sqlSession.commit();
		sqlSession.close();}@TestpublicvoidTest04(){//deleteSqlSession sqlSession=MybatisUtil.getSqlSession();int result= sqlSession.delete("a.b.c.scStudent",11);System.out.println(result);
		sqlSession.commit();
		sqlSession.close();}@TestpublicvoidTest05(){//selectListSqlSession sqlSession=MybatisUtil.getSqlSession();List<Student> students= sqlSession.selectList("a.b.c.selectListStudent");for(Student s: students){System.out.println(s);}
		sqlSession.close();}@TestpublicvoidTest06(){//selectMapSqlSession sqlSession=MybatisUtil.getSqlSession();Map<Integer,Student> map= sqlSession.selectMap("a.b.c.selectMapStudent","age");//遍历mapSet<Map.Entry<Integer,Student>> entrySet= map.entrySet();for(Map.Entry<Integer,Student> entry: entrySet){System.out.println("key:"+entry.getKey()+",value:"+entry.getValue().toString());}
		sqlSession.close();}/**
	 * 模糊查询
	 */@TestpublicvoidTest07(){//selectMapSqlSession sqlSession=MybatisUtil.getSqlSession();List<Student> students= sqlSession.selectList("a.b.c.mhSelectStudent","李");for(Student s: students){System.out.println(s);}
		sqlSession.close();}/**
	 * mapper的动态代理(自动为我们生成StudentDaoImpl)
	 */@TestpublicvoidTest08(){SqlSession sqlSession=MybatisUtil.getSqlSession();//使用mapper动态代理技术生成对应接口的实现类StudentMapper sd= sqlSession.getMapper(StudentMapper.class);
		sd.saveStudent(newStudent(15,"李思思",23,90.01));
		sqlSession.commit();System.out.println(sd);}}

java工具类:

packagecom.zx.mybatis.util;importjava.io.IOException;importjava.io.InputStream;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;publicclassMybatisUtil{privatestaticString resource="mybatis.xml";privatestaticSqlSessionFactory sqlSessionFactory=null;/**
	 * 获取sqlSession
	 * @return
	 */publicstaticSqlSessiongetSqlSession(){if(sqlSessionFactory==null){try{InputStream inputStream=Resources.getResourceAsStream(resource);
				sqlSessionFactory=newSqlSessionFactoryBuilder().build(inputStream);}catch(IOException e){
  • 作者:day码云
  • 原文链接:https://blog.csdn.net/m0_45226909/article/details/122131268
    更新时间:2022-08-13 13:48:56