基本使用
mybatis 的常用注解:
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
UserDao.java
@CacheNamespace(blocking=true)
public interface UserDao {
@Select("select * from user")
@Results(id = "userMap",
value = {
@Result(id=true,column="id",property="id"),
@Result(column="username",property="username"),
@Result(column="sex",property="sex"),
@Result(column="address",property="address"),
@Result(column="birthday",property="birthday")
})
List<User> findAll();
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
@Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
@SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class, before = false, statement = { "select last_insert_id()" })
int saveUser(User user);
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ")
int updateUser(User user);
@Delete("delete from user where id = #{uid} ")
int deleteUser(Integer userId);
@Select("select count(*) from user ")
int findTotal();
@Select("select * from user where username like #{username} ")
List<User> findByName(String name);
@Select("select * from user")
@Results(id="userAccount",
value= {
@Result(id=true,column="id",property="id"),
@Result(column="username",property="username"),
@Result(column="sex",property="sex"),
@Result(column="address",property="address"),
@Result(column="birthday",property="birthday"),
@Result(column="id",property="accounts",
many=@Many(
select="com.sibd.dao.AccountDao.findByUid",
fetchType= FetchType.LAZY
) )
})
List<User> findAll_Account();
}
SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式。
statement是要运行的SQL语句,它的返回值通过resultType来指定
before表示查询语句statement运行的时机
keyProperty表示查询结果赋值给代码中的哪个对象,keyColumn表示将查询结果赋值给数据库表中哪一列
keyProperty和keyColumn都不是必需的,有没有都可以
before=true,插入之前进行查询,可以将查询结果赋给keyProperty和keyColumn,赋给keyColumn相当于更改数据库
befaore=false,先插入,再查询,这时只能将结果赋给keyProperty
赋值给keyProperty用来“读”数据库,赋值给keyColumn用来写数据库
selectKey的两大作用:1、生成主键;2、获取刚刚插入数据的主键。
使用selectKey,并且使用MySQL的last_insert_id()函数时,before必为false,也就是说必须先插入然后执行last_insert_id()才能获得刚刚插入数据的ID
这个注解的功能与
<selectKey>
标签完全一致,用在已经被 @Insert 或 @InsertProvider 或 @Update 或 @UpdateProvider 注解了的方法上。若在未被上述四个注解的方法上作 @SelectKey 注解则视为无效。如果你指定了 @SelectKey 注解,那么 MyBatis 就会忽略掉由 @Options 注解所设置的生成主键或设置(configuration)属性。属性有:
statement 填入将会被执行的 SQL 字符串数组,
keyProperty 填入将会被更新的参数对象的属性的值,
before 填入 true 或 false 以指明 SQL 语句应被在插入语句的之前还是之后执行。
resultType 填入 keyProperty 的 Java 类型
SqlMapConfig 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置 properties 文件的位置 -->
<properties resource="jdbcConfig.properties"></properties>
<!-- 配置别名的注册 -->
<typeAliases>
<package name="com.domain"/>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置 mysql 的环境 -->
<environment id="mysql">
<!-- 配置事务的类型是 JDBC -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 配置映射信息 -->
<mappers>
<!-- 配置 dao 接口的位置,它有两种方式
第一种:使用 mapper 标签配置 class 属性
第二种:使用 package 标签,直接指定 dao 接口所在的包
-->
<package name="com.dao"/>
</mappers>
</configuration>
使用注解实现复杂关系映射开发
@Results 注解
代替的是标签<resultMap>
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({@Result(),@Result()})或@Results(@Result())
@Resutl 注解
代替了 <id>标签和<result>标签
@Result 中 属性介绍:
id 是否是主键字段
column 数据库的列名
property 需要装配的属性名
one 需要使用的@One 注解(@Result(one=@One)()))
many 需要使用的@Many 注解(@Result(many=@many)()))
@One 注解(一对一)
代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One 注解属性介绍:
select 指定用来多表查询的 sqlmapper
fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。。
使用格式:
@Result(column=" ",property="",one=@One(select=""))
@Many 注解(多对一)
代替了<Collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义;
使用格式:
@Result(property="",column="",many=@Many(select=""))
一对一的复杂关系映射
AccountDao.java
public interface AccountDao {
@Select("select * from account")
@Results(id="accountMap",
value= {
@Result(id=true,column="id",property="id"),
@Result(column="uid",property="uid"),
@Result(column="money",property="money"),
@Result(column="uid",
property="user",
one=@One(select="com.sibd.dao.UserDao.findById", fetchType= FetchType.LAZY)
)
})
List<Account> findAll();
@Select("select * from account where uid = #{uid} ")
List<Account> findByUid();
}
一对多的复杂关系映射
@Select("select * from user")
@Results(id="userAccount",
value= {
@Result(id=true,column="id",property="id"),
@Result(column="username",property="username"),
@Result(column="sex",property="sex"),
@Result(column="address",property="address"),
@Result(column="birthday",property="birthday"),
@Result(column="id",property="accounts",
many=@Many(
select="com.sibd.dao.AccountDao.findByUid",
fetchType= FetchType.LAZY
) )
})
List<User> findAll_Account();
@Many:
相当于<collection>
的配置java
select 属性:代表将要执行的 sql 语句
fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值
二级缓存
SqlMapConfig 中开启二级缓存支持
<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 -->
<setting name="cacheEnabled" value="true"/>
</settings>
在持久层接口中使用注解配置二级缓存
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface UserDao {}