Mybatis 注解开发


这几年来注解开发越来越流行,Mybatis 也可以使用注解开发方式,这样我们就可以减少编写 Mapper 映射文件了。本次我们先围绕一些基本的 CRUD 来学习,再学习复杂映射关系及延迟加载。

1 mybatis 的常用注解说明

@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider:  实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用 

2 使用 Mybatis 注解实现基本 CRUD

单表的 CRUD 操作是最基本的操作,前面我们的学习都是基于 Mybaits 的映射文件来实现的。

2.1 编写实体类

package com.zjw.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

    private Integer userId;
    private String userName;
    private String userAddress;
    private String userSex;
    private Date userBirthday;

    public User() {
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public Date getUserBirthday() {
        return userBirthday;
    }

    public void setUserBirthday(Date userBirthday) {
        this.userBirthday = userBirthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", username='" + userName + '\'' +
                ", userAddress='" + userAddress + '\'' +
                ", userSex='" + userSex + '\'' +
                ", userBirthday=" + userBirthday +
                '}';
    }
}

2.2 使用注解方式开发持久层接口


/**
 * 在mybatis中针对CRUD一共有四个注解
 * @Select @Insert @Update @Delete
 */
public interface IUserDao {

    /**
     * 查询所有用户
     * @return
     */

//    只有一个value需要赋值时,value可以省略
//    @Select(value = "")
    @Select("select * from user")
    @Results(
            id = "userMap",
            value = {
                    @Result(id = true,column = "id",property = "userId"),
                    @Result(column = "username",property = "userName"),
                    @Result(column = "birthday",property = "userBirthday"),
                    @Result(column = "sex",property = "userSex"),
                    @Result(column = "address",property = "userAddress"),
            }
    )
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     */
    @Insert("INSERT INTO user(username,address,sex,birthday) VALUES (#{userName},#{userAddress},#{userSex},#{userBirthday})")
    @SelectKey(keyColumn = "id",keyProperty = "userId",resultType = Integer.class,before = false,statement = {"select last_insert_id()"})
    void saveUser(User user);

    /**
     * 更新用户
     * @param user
     */
    @Update("UPDATE user set username=#{userName},address=#{userAddress},sex=#{userSex},birthday=#{userBirthday} WHERE id=#{userId}")
    void updateUser(User user);

    /**
     * 删除用户
     * @param id
     */
    @Delete("Delete FROM user WHERE id=#{userId}")
    void deleteUser(Integer id);

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Select("SELECT * FROM user WHERE id=#{userId}")
    @ResultMap("userMap")
    User findById(Integer id);

    /**
     * 根据名字模糊查询用户
     * @param name
     * @return
     */
    //方法一:传入的name需要加%号
//    @Select("SELECT * FROM user WHERE username LIKE #{name}")
    //方法二:并不需要加%号,防止sql注入
    @Select("SELECT * FROM user WHERE username LIKE '%${value}%'")
    @ResultMap("userMap")
    List<User> findByName(String name);


    /**
     * 查询用户总记录数
     * @return
     */
    @Select("SELECT COUNT(*) FROM user")
    int findTotal();
}

2.3 编写 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 resource="jdbcConfig.properties"/>

    <!--配置别名,实体类所在位置-->
    <typeAliases>
        <package name="com.zjw.domain"/>
    </typeAliases>

    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <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>
    
    <!-- 指定带有注解的dao接口所在位置 -->
    <mappers>
        <package name="com.zjw.dao"/>
    </mappers>
    
</configuration>

2.4 编写测试方法


public class AnnotationCRUDTest {

    private InputStream in ;
    private SqlSessionFactory factory ;
    private SqlSession session ;
    private IUserDao userDao ;

    @Before
    public void init() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        userDao = session.getMapper(IUserDao.class);
    }

    @After
    public void destroy() throws IOException {
        session.commit();
        session.close();
        in.close();
    }

    /**
     * 测试查询所有用户
     */
    @Test
    public void testFindAll(){
        List<User> userList = userDao.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }


    /**
     * 测试保存用户
     */
    @Test
    public void testSave(){
        User user = new User();
        user.setUserName("mybatis annotation");
        user.setUserAddress("上海");
        userDao.saveUser(user);
        System.out.println(user);
    }

    /**
     * 测试更新用户
     */
    @Test
    public void testUpdate(){
        User user = new User();
        user.setUserId(57);
        user.setUserName("mybatis");
        user.setUserAddress("上海");
        user.setUserBirthday(new Date());
        user.setUserSex("男");

        userDao.updateUser(user);
    }


    /**
     * 测试删除用户
     */
    @Test
    public void testDelete(){
        userDao.deleteUser(57);
    }

    /**
     * 测试查找单个用户
     */
    @Test
    public void testFindById(){
        User user = userDao.findById(41);
        System.out.println(user);

    }

    /**
     * 根据名字模糊查询用户
     */
    @Test
    public void testFindByName(){
//        List<User> users = userDao.findByName("%王%");
        List<User> users = userDao.findByName("王");
        for (User user : users){
            System.out.println(user);
        }
    }

    /**
     * 查询总记录数
     */
    @Test
    public void testFindTotal(){
        System.out.println(userDao.findTotal());
    }

}

3 使用注解实现复杂关系映射开发

实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap>来实现,在使用注解开发时我们需要借助@Results 注解,@Result 注解,@One 注解,@Many 注解。

@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 注解(一对一)
代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
 @One 注解属性介绍:
  select 指定用来多表查询的 sqlmapper
  fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。。
 使用格式:
  @Result(column=" ",property="",one=@One(select=""))

@Many 注解(多对一)
 代替了标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
 注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义;
 使用格式:
  @Result(property="",column="",many=@Many(select=""))

3.2 使用注解实现一对一复杂关系映射及延迟加载

需求:

加载账户信息时并且加载该账户的用户信息,根据情况可实现延迟加载。(注解方式实现)

3.2.1 添加 User 实体类及 Account 实体类


public class User implements Serializable {

    private Integer userId;
    private String userName;
    private String userAddress;
    private String userSex;
    private Date userBirthday;

    //一对多关系映射:一个用户对应多个账户
    private List<Account> accounts ;

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public Date getUserBirthday() {
        return userBirthday;
    }

    public void setUserBirthday(Date userBirthday) {
        this.userBirthday = userBirthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userAddress='" + userAddress + '\'' +
                ", userSex='" + userSex + '\'' +
                ", userBirthday=" + userBirthday +
                '}';
    }
}

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;

    //多对一(mybatis中称为一对一)的映射:一个账户只能属于一个用户
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                '}';
    }
}

3.2.2 添加账户的持久层接口并使用注解配置

public interface IAccountDao {

    /**
     * 查询所有账户信息
     * @return
     */
    @Select("SELECT * FROM account")
    @Results(id = "AccountMap", value = {
            @Result(id = true ,property = "id" ,column = "id"),
            @Result(property = "uid" ,column = "uid"),
            @Result(property = "money" ,column = "money"),
            @Result(property ="user", column = "uid", one = @One(select = "com.zjw.dao.IUserDao.findById" ,fetchType = FetchType.EAGER))

    })
    List<Account> findAll();

    /**
     * 通过用户id查找用户的账户
     * @param uid
     * @return
     */
    @Select("SELECT * FROM account WHERE uid = #{uid}")
    List<Account> findAccountByUid(Integer uid);
}

fetchType = FetchType.EAGER指明加载方式。EAGERLAZY两种。

3.2.3 添加用户的持久层接口并使用注解配置


/**
 * 在mybatis中针对CRUD一共有四个注解
 * @Select @Insert @Update @Delete
 */

@CacheNamespace(blocking = true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {

    /**
     * 查询所有用户
     * @return
     */

//    只有一个value需要赋值时,value可以省略
//    @Select(value = "")
    @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(property = "accounts",column = "id",
                            many = @Many(select ="com.zjw.dao.IAccountDao.findAccountByUid",
                                        fetchType = FetchType.LAZY))
            }
    )
    List<User> findAll();

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Select("SELECT * FROM user WHERE id=#{id}")
//    @ResultMap(value = "UserMap")
//    @ResultMap("UserMap")
    @ResultMap(value = {"UserMap"})
    User findById(Integer id);

    /**
     * 根据名字模糊查询用户
     * @param name
     * @return
     */
    //方法一:传入的name需要加%号
    @Select("SELECT * FROM user WHERE username LIKE #{name}")
    //方法二:并不需要加%号,防止sql注入
//    @Select("SELECT * FROM user WHERE username LIKE '%${value}%'")
    @ResultMap(value = {"UserMap"})
    List<User> findByName(String name);

}

3.2.4 测试类

public class AccountTest {

    private InputStream in ;
    private SqlSessionFactory factory ;
    private SqlSession session ;
    private IAccountDao accountDao;

    @Before
    public void init() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        accountDao = session.getMapper(IAccountDao.class);
    }

    @After
    public void destroy() throws IOException {
        session.commit();
        session.close();
        in.close();
    }


    @Test
    public void testFindAll(){
        //立即加载,会同时查询用户信息
        List<Account> accounts = accountDao.findAll();
//        for (Account account : accounts) {
//            System.out.println("----每个账户的信息----");
//            System.out.println(account);
//            System.out.println(account.getUser());
//        }
    }

}
public class UserTest {

    private InputStream in ;
    private SqlSessionFactory factory ;
    private SqlSession session ;
    private IUserDao userDao ;

    @Before
    public void init() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        userDao = session.getMapper(IUserDao.class);
    }

    @After
    public void destroy() throws IOException {
        session.commit();
        session.close();
        in.close();
    }


    @Test
    public void testFindAll(){
        List<User> users = userDao.findAll();
        //验证延迟加载
//        for (User user : users) {
//            System.out.println(user);
//            System.out.println(user.getAccounts());
//        }
    }
}
public class SecondLevelCatchTest {

    private InputStream in ;
    private SqlSessionFactory factory ;
    private SqlSession session ;
    private IUserDao userDao ;

    @Before
    public void init() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        userDao = session.getMapper(IUserDao.class);
    }

    @After
    public void destroy() throws IOException {

        in.close();
    }


    /**
     * 测试查找单个用户,验证二级缓存
     */
    @Test
    public void testFindById(){
        //第一次查询数据库
        User user = userDao.findById(54);
        System.out.println(user);

        session.close();
        session = factory.openSession();
        IUserDao userDao = session.getMapper(IUserDao.class);
        //第二次用cache中取值
        User user2 = userDao.findById(54);
        System.out.println(user2);

        System.out.println(user == user2);

        session.commit();
        session.close();

    }


}
posted @ 2020-11-08 15:40  雨中遐想  阅读(206)  评论(0编辑  收藏  举报