1. MyBatis的常用注解
MyBatis的常用注解:
- @Insert:实现新增
- @Update:实现更新
- @Delete:实现删除
- @Select:实现查询
- @Result:结果集封装
- @Results:与@Result一起使用,封装多个结果集
- @ResultMap:引用@Results定义的封装
- @One:一对一结果集封装
- @Many:一对多结果集封装
- @CacheNamespace:实现注解二级缓存的使用
编写实体类:
public class User implements Serializable {
//此处我们故意和数据库表的列名不一致
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
//省略 get和 set方法
}
编写持久层接口:
public interface IUserDao {
/**
* @Results注解:代替了 <resultMap>标签
* @Resutl注解:代替了 <id>标签和 <result>标签
* id:是否是主键字段,默认为 false
* column:数据库的列名
* property:需要装配的实体类属性名
*/
@Select("select * from user")
@Results(id="userMap", value={
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday")
})
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})")
void saveUser(User user);
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday}
where id=#{id} ")
void updateUser(User user);
@Delete("delete from user where id = #{uid} ")
void deleteUser(Integer userId);
@Select("select count(*) from user ")
int findTotal();
// @Select("select * from user where username like '%${value}%' ")
@Select("select * from user where username like #{username} ")
@ResultMap("userMap")
List<User> findByName(String username);
}
编写SqlMapConfig.xml配置文件:
<?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>
<!-- 配置 mybatis的环境 -->
<environments default="mysql">
<!-- 配置 mysql的环境 -->
<environment id="mysql">
<!-- 配置事务的类型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置连接数据库的信息:用的是数据源(连接池) -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/joker"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 配置映射信息 -->
<mappers>
<package name="com.joker.dao"/>
</mappers>
</configuration>
编写测试代码:
public class AnnotationCRUDTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}
@After
public void destroy()throws Exception{
session.commit();
session.close();
in.close();
}
@Test
public void testFindAll() {
List<User> users = userDao.findAll();
for(User user : users) {
System.out.println(user);
}
}
@Test
public void testSave(){
User user = new User();
user.setUsername("张三");
userDao.saveUser(user);
}
@Test
public void testUpdate(){
User user = new User();
user.setId(1);
user.setUsername("李四");
user.setAddress("北京");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
}
@Test
public void testDelete(){
userDao.deleteUser(1);
}
@Test
public void testFindOne(){
User user = userDao.findById(1);
System.out.println(user);
}
@Test
public void testFindByName(){
// List<User> users = userDao.findUserByName("张");
List<User> users = userDao.findUserByName("%张%");
for(User user : users){
System.out.println(user);
}
}
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
}
}
2. MyBatis一对一(多对一)的注解
实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap>来实现,在使用注解开发时我们需要借助@Results注解、@Result注解、@One注解、@Many注解。
编写实体类:
public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
//省略 get和 set方法
}
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//多对一关系映射:从表方应该包含一个主表方的对象引用
private User user;
//省略 get和 set方法
}
编写持久层接口:
public interface IUserDao {
@Select("select * from user")
@Results(id="userMap", value={
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday")
})
List<User> findAll();
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
}
public interface IAccountDao {
/**
* @One注解:代替了 <assocation>标签,在注解中用来指定子查询返回单一对象
* select:指定用来多表查询的 sqlmapper
* fetchType:是否延迟加载
*/
@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.joker.dao.IUserDao.findById",fetchType=FetchType.EAGER))
})
List<Account> findAll();
}
编写测试代码:
@Test
public void testFindAll() {
List<Account> accounts = accountDao.findAll();
for(Account account : accounts) {
System.out.println(account);
System.out.println(account.getUser());
}
}
3. MyBatis一对多的注解
编写实体类:
public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
//一对多关系映射:主表方法应该包含一个从表方的集合引用
private List<Account> accounts;
//省略 get和 set方法
}
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//省略 get和 set方法
}
编写持久层接口:
public interface IUserDao {
/**
* @Many注解:代替了 <Collection>标签,在注解中用来指定子查询返回对象集合
* select:指定用来多表查询的 sqlmapper
* fetchType:是否延迟加载
*/
@Select("select * from user")
@Results(id="userMap", value={
@Result(id=true,column="id",property="userId"),
@Result(column="username",property="userName"),
@Result(column="sex",property="userSex"),
@Result(column="address",property="userAddress"),
@Result(column="birthday",property="userBirthday"),
@Result(column="id",property="accounts",
many=@Many(select="com.joker.dao.IAccountDao.findByUid",fetchType=FetchType.LAZY))
})
List<User> findAll();
}
public interface IAccountDao {
@Select("select * from account")
List<Account> findAll();
@Select("select * from account where uid = #{uid} ")
List<Account> findByUid(Integer userId);
}
编写测试代码:
@Test
public void testFindAll() {
List<User> users = userDao.findAll();
for(User user : users) {
System.out.println(user);
System.out.println(user.getAccounts());
}
}
4. MyBatis二级缓存的注解
在SqlMapConfig.xml文件开启二级缓存:
<!-- 因为 cacheEnabled的取值默认就为 true,所以这一步可以省略不配置 -->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
在持久层接口中使用注解配置二级缓存:
@CacheNamespace(blocking=true)
public interface IUserDao {
}