欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis04—注解开发实现CRUD以及实现一对一、一对多及多对多复杂关系映射

程序员文章站 2022-07-12 22:37:29
...

mybatis常用注解说明

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

Mybatis注解实现CRUD

User实体类:

package com.review.domain;

import java.util.*;

public class User {
    private Integer userId;
    private String userName;
    private Date userBirthday;
    private String userSex;
    private String userAddress;

    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 Date getUserBirthday() {
        return userBirthday;
    }

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

    public String getUserSex() {
        return userSex;
    }

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

    public String getUserAddress() {
        return userAddress;
    }

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

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

IUserDao持久层接口:

package com.review.dao;

import com.review.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;


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 = "birthday",property = "userBirthday"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "address",property = "userAddress")
    })
    List<User> findAll();

    /**
     * 根据id查询
     */
    @Select("select *from user where id=#{uid}")
    @ResultMap("userMap")
    User findById(Integer userId);

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

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

    /**
     * 删除用户
     */
    @Delete("delete from user where id=#{uid}")
    @ResultMap("userMap")
    void deleteUser(Integer userId);
    /**
     * 用户模糊查询
     */
    @Select("select * from user where username like #{username}")
    @ResultMap("userMap")
    List<User> findByName(String username);
    /**
     * 使用聚合函数查询总记录条数
     */
    @Select("select count(*) from user")
    //@ResultMap("userMap")
    int findTotal();
}


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="db.properties"></properties>

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 告知mybatis映射配置的位置 -->
    <mappers>
        <mapper class="com.review.dao.IUserDao"/>
    </mappers>
</configuration>

测试类:

package com.review.test;


import com.review.dao.IUserDao;
import com.review.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisTest {
    private InputStream in;
    private SqlSessionFactoryBuilder builder;
    private SqlSessionFactory factory;
    private SqlSession session;
    private IUserDao userDao;

    @Test
    public void testFindAll() throws Exception {
        List<User> users = userDao.findAll();
        for(User user:users){
            System.out.println(user);
        }
    }

    @Test
    public void testFindOne() throws Exception {
        User user = userDao.findById(48);
        System.out.println(user);
    }

    @Test
    public void testSave() throws Exception {
        User user = new User();
        user.setUserName("周杰伦");
        user.setUserAddress("*省台北市");
        user.setUserSex("男");
        user.setUserBirthday(new Date());
        userDao.saveUser(user);
        System.out.println(user);
    }

    @Test
    public void testUpdateUser() throws Exception {
        User user = userDao.findById(42);
        user.setUserName("小王");
        userDao.updateUser(user);
        System.out.println(user);
    }

    @Test
        public void testDeleteUser() throws Exception {
            userDao.deleteUser(62);
    }

    @Test
    public void testFindByName() throws Exception {
        List<User> users = userDao.findByName("%王%");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testFindTotal() throws Exception {
        int res = userDao.findTotal();
        System.out.println(res);
    }

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

    }

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

注解实现一对一复杂关系映射

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

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private double money;
//    一个账户对应一个用户
    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 +
                '}';
    }
}

public class User implements Serializable {
    private Integer userId;
    private String userName;
    private Character userSex;
    private String userAddress;
    private Date userBirthday;

    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 Character getUserSex() {
        return userSex;
    }

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

    public String getUserAddress() {
        return userAddress;
    }

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

    public Date getUserBirthday() {
        return userBirthday;
    }

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

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

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

public interface IAccountDao {
    /**
     * 查询所有账户信息
     * @return
     */
    @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.review.dao.IUserDao.findById",fetchType = FetchType.EAGER))
    })
    List<Account> findAll();
}

public interface IUserDao {
    /**
     * 根据id查询一个用户
     * @return
     */
    @Select("select * from user where id = #{uid} ")
    @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")})
    User findById(Integer userId);
}

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="db.properties"></properties>
<!--    <typeAliases>-->
<!--        <package name="com.review.domain"></package>-->
<!--    </typeAliases>-->

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 告知mybatis映射配置的位置 -->
    <mappers>
        <mapper class="com.review.dao.IAccountDao"/>
        <mapper class="com.review.dao.IUserDao"/>
    </mappers>
</configuration>

测试类:

@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());
        }
    }

控制台打印结果:
Mybatis04—注解开发实现CRUD以及实现一对一、一对多及多对多复杂关系映射

注解实现一对多复杂关系映射

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

public class User implements Serializable {
    private Integer userId;
    private String userName;
    private Character userSex;
    private String userAddress;
    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 Character getUserSex() {
        return userSex;
    }

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

    public String getUserAddress() {
        return userAddress;
    }

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

    public Date getUserBirthday() {
        return userBirthday;
    }

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

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

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

    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 +
                '}';
    }
}

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

public interface IUserDao {
    /**
     * 查询所有用户
     * @return
     */
    @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.review.dao.IAccountDao.findById",fetchType = FetchType.EAGER))
    })
    List<User> findAll();
}

public interface IAccountDao {
    /**
     * 查询所有账户信息
     * @return
     */
    @Select("select * from account where UID=#{id}")
    @Results(id = "accountMap",value = {
            @Result(id = true,column = "ID",property = "id"),
            @Result(column = "UID",property = "uid"),
            @Result(column = "MONEY",property = "money")
    })
    List<Account> findById();
}

测试类:

@Test
    public void testFindAll() {
        List<User> users = userDao.findAll();
        for (User user:users){
            System.out.println();
            System.out.println("----每个用户的信息----");
            System.out.println(user);
            System.out.println(user.getAccounts());
        }
    }

控制台打印结果:
Mybatis04—注解开发实现CRUD以及实现一对一、一对多及多对多复杂关系映射

mybatis基于注解的二级缓存

在SqlMapConfig中开启二级缓存支持:

<!--    配置二级缓存-->
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>

在持久层接口中使用注解配置二级缓存:

@CacheNamespace(blocking=true)//mybatis基于注解方式实现配置二级缓存 
public interface IUserDao {}
相关标签: Mybatis