mybatis mapper映射文件全解

  

目录


select、update、delete、insert

设置参数类型以及取值

基本数据类型

对象数据类型

map数据类型

#{  } 和 ${  } 的区别

ResultMap

Auto-mapping

cache

 

 


 

 

 

 

select、update、delete、insert

  这分别对应有四个标签

  对于 int SqlSession.select(String statement) int SqlSession.select(String statement, Object parameter) int SqlSession.insert(String statement) int SqlSession.insert(String statement, Object parameter) int SqlSession.update(String statement) int SqlSession.update(String statement, Object parameter) int SqlSession.delete(String statement) int SqlSession.delete(String statement, Object parameter)

  

 

设置参数类型以及取值

  设置参数类型,是通过设置parameterType的值,设置的类型不同,sql中取值的方式也有所区别。

  parameterType属性可以有下面几种取值:

  1、基本数据类型

    比如int、double,其实应该写为Integer、Double,但是有自动装箱功能,所以可以直接写基本数据类型。

    sql取值的方式:对于这种的参数,在接收传入的参数值时,可以使用#{index}来获取,注意,index从0开始计数,如果只有一个参数,那么index可以写成任意名称。



	
	
	
	

  

  2、Object类型

    可以写实体类(如果没有配置alias,需要写全路径),比如cn.ganlixin.pojo.Person类。

    sql取值的方式:对于对象这种类型,可以使用#{property}去访问实体类中的property属性值,比如#{age},可以获取Person的age属性值。


	

    简单测试:

String method = "cn.ganlixin.mapper.PersonMapper.selectPersonByName";
Person person = new Person();
person.setName("aaaa");
person = (Person)  session.selectOne(method, person);

  

  3、map类型

    将要传入一个数据,封装到一个map中,然后再传入即可。

    sql取值的方式:对于map的取值,和object的取值类似,使用#{key}即可获取map中key对应value。


	

    简单测试:

String method = "cn.ganlixin.mapper.PersonMapper.selectPersonByName";
Map data = new HashMap<>();
data.put("name", "aaaa");
Person person = (Person)  session.selectOne(method, data);

  

  4、#{  } 和 ${  } 的区别

  需要注意的是,sql中取值可以使用#{  } 和 ${  }两种方式,区别在于:

  1、#{  } 会使用预处理操作,而${  }不会进行预处理操作。

  2、${  } 只是很简单的使用字符串拼接

select * from person where name='${name}'
如果上面不适用引号将${name}括起来,那么就会将${name}的值当做字段名,而不是字段值

select * from person where name=${0}
上面这条sql语句,并不会使用传入的第1个参数,而是真的name=0

  

 

ResultMap

   关于resultMap的使用,可以查看:

  mybatis 使用resultMap实现表间关联

 

 

Auto-mapping

   关于auto-mapping的使用,可以查看:

    mybatis 使用auto mapping原理实现表间关联

 

 

cache

  mybatis中的缓存有两种,一级缓存和二级缓存。

  可以查看:mybatis 使用缓存策略

   

 

转载于:https://www.cnblogs.com/-beyond/p/10114730.html

你可能感兴趣的:(mybatis mapper映射文件全解)