Mybatis终极案例之注解开发

Mybatis终极案例之注解开发

一、注解开发实现CURD操作
1.环境搭建

参考入门案例,环境搭建主要分为如下几步:

1.配置pom.xml

<packaging>jar</packaging>
<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.19</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
</dependencies>

2.配置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>
    <!-- 导入数据库连接信息 -->
    <properties resource="jdbcConfig.properties"></properties>

    <!-- 配置延迟加载和二级缓存 -->
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <!-- 给实体类取别名,该包下的实体类都会具有别名 -->
    <typeAliases>
        <package name="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 接口的位置,它有两种方式
        第一种:使用 mapper 标签配置 class 属性
        第二种:使用 package 标签,直接指定 dao 接口所在的包
     -->
    <mappers>
        <package name="dao"/>
    </mappers>

</configuration>

之所以采用外部文件(jdbcConfig.propertities)的方式对数据连接信息进行修改,是为了之后修改时更加方便,内容如下:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=12345678

log4j的配置文件(log4j.properties)如下:

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

上述三个文件都在Resources目录下,同时注意:对于同一个dao接口映射配置文件和注解的方式只能选一种,如果采用注解的方式,该dao接口对应得resource就不能包括映射配置文件。

3.新建实体类

在src/main/java目录下,新建实体类domain.User。

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

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

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


}
2.配置数据库列名和实体关系类名的映射

由于实体类属性名和数据库列名并不一致,所以不能像入门案例一样,只使用Select标签。需要使用Results标签。在src/main/java目录下,新建接口dao.IUserDao:

public interface IUserDao {

    /**
     * 查询所有用户
     * 实体类属性名和数据库列名不一致,通过Results注解进行配置
     * @return
     */
    @Select("select * from user")
    //Results的id相当于名称,value属性是实体类属性和数据库列名的映射关系
    @Results(id = "userMap", value = {
            //Result的id表示是否是主键,默认为false,column是数据库列名,property是实体类属性
            @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> findAllUsers();
}
3.测试

在test/java目录下,新建测试类UserTest:

public class UserTest {
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession sqlSession;
    private IUserDao userDao;

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

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

    @Test
    public void testFindAllUsers() {
        List<User> users = userDao.findAllUsers();
        for (User user : users
        ) {
            System.out.println(user);
        }
    }

查询所有用户的结果

4.更加复杂的查询

我们已经实现了最基本的查询操作,现在在IUserDao接口中,添加更多的方法,以实现更加复杂的CRUD:

/**
 * 根据用户id查询用户
 *  无需再次重写Results注解,可以通过ResultMap注解引用Results
 * @param userId
 */
@Select("select * from user where id = #{uid}")
@ResultMap("userMap")
User findById(Integer userId);

/**
 * 模糊查询
 *  参数是基本属性,#{}中的名称随意
 * @param userName
 * @return
 */
@Select("select * from user where username like #{username}")
@ResultMap("userMap")
List<User> findByName(String userName);

/**
 * 查询用户总数
 *
 * @return
 */
@Select("select count(id) from user")
int findTotal();

/**
 * 插入用户
 *
 * @param user
 */
@Insert("insert into user(username, sex, address, birthday) values " +
        "(#{userName}, #{userSex}, #{userAddress}, #{userBirthday}) ")
@ResultMap("userMap")
void insertUser(User user);


/**
 * 删除用户
 *
 * @param userId
 */
@Delete("delete from user where id = #{id} ")
@ResultMap("userMap")
void deleteUser(Integer userId);

/**
 * 更新用户
 * 参数是实体类,使用的OGNL表达式,因此#{}中的名称必须是属性名
 * @param user
 */
@Update("update user set username = #{userName}, address = #{userAddress}, " +
        " sex = #{userSex}, birthday = #{userBirthday} where id = #{userId}")
@ResultMap("userMap")
void updateUser(User user);


/**
 * 保存操作
 * 通过SelectKey可以获取保存用户时,数据库自动更新的id字段
 * @param user 
 * @return 影响数据库记录的行数
 */
@Insert("insert into user(username, sex, birthday, address) values (#" +
        "{userName}, #{userSex},#{userBirthday},#{userAddress} )")
@SelectKey(keyColumn = "id", keyProperty = "userId", resultType = Integer.class,
        before = false, statement = {"select last_insert_id()"})
int saveUser(User user);

在测试类UserTest中添加测试:

/**
 * 测试根据id查询用户
 */
@Test
public void testFindById(){
    User user = userDao.findById(41);
    System.out.println(user);
}

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

/**
 * 查询数据库中用户总数
 */
@Test
public void testFindTotal(){
    int total = userDao.findTotal();
    System.out.print("数据库中用户总数为:");
    System.out.println(total);
}

/**
 * 测试插入用户
 */
@Test
public void testInsertUser(){
    User user = new User();
    user.setUserName("插入的用户");
    user.setUserAddress("湖北省武汉市洪山区");
    userDao.insertUser(user);
}

/**
 * 测试更新用户
 */
@Test
public void testUpdateUser(){
    User user = new User();
    user.setUserId(59);
    user.setUserName("更新的用户");
    user.setUserAddress("北京市海淀区");
    user.setUserSex("男");
    user.setUserBirthday(new Date());
    userDao.updateUser(user);
}

/**
 * 测试删除用户
 */
@Test
public void testDeleteUser(){
    User user = new User();
    userDao.deleteUser(60);
}

/**
 * 测试保存用户
 */
@Test
public void testSaveUser(){
    User user = new User();
    user.setUserName("保存的用户");
    user.setUserAddress("武汉市武昌区");
    user.setUserSex("女");
    user.setUserBirthday(new Date());
    int res = userDao.saveUser(user);
    System.out.println("影响数据库记录的行数:"+res);
    System.out.println("插入的主键值:"+user.getUserId());
}
二、注解开发实现复杂关系映射
1.一对一多表查询

1.新建Account类

在src/main/java目录下的domain包下,新建实体类Account:

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

  //从表实体应包含主表实体的引用
    private User user;

    public Integer getUid() {
        return uid;
    }

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

    public Integer getId() {
        return id;
    }

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

    public Double getMoney() {
        return money;
    }

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

    public User getUser() {
        return user;
    }

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

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

2.添加dao接口

在src/main/java目录下的dao包下,新建接口IAccountDao:

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的one属性,表示是一对一的关系
            //此时column表示查询所需要的参数所对应的数据库列名
            //property表示的是从表实体对主表实体的引用的属性名
            @Result(column = "uid", property = "user",
                    //One的select属性,表示对于主表实体所对应的查询方法
                    //fetchType属性是加载的方式:LAZY(延迟)、EAGER(立即)、DEFAULT(默认)
                    //一对一默认是立即加载,一对多默认是延迟加载
                    one = @One(select = "dao.IUserDao.findById",
                            fetchType = FetchType.LAZY)
            )
    })
    List<Account> findAccountsWithUser();

}

3.测试

在test/java目录下,新建测试类AccountTest:

public class AccountTest {
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private IAccountDao accountDao;

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

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

    /**
     * 测试查询带有用户信息的账户信息
     */
    @Test
    public void testFindAccountsWithUser() {
        List<Account> accounts = accountDao.findAccountsWithUser();
        for (Account account : accounts
        ) {
            System.out.println(account.getId());
            if(account.getUid() == 41)
                System.out.println(account.getUser());
        }
    }
}

一对一延迟加载

2.一对多多表查询

1.在IAccountDao接口中添加根据用户id查询的方法

/**
 * 根据用户Id查询账户信息
 * @param uerId
 * @return
 */
@Select("select * from account where uid = #{uid}")
List<Account> findByUid(Integer uerId);

2.在IUserDao接口中添加一对多查询的方法

/**
 * 查询带有账户信息的用户信息
 * @return
 */
@Select("select * from user")
@Results(id = "userMap1", 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 = @Many(select = "dao.IAccountDao.findByUid",
                        fetchType = FetchType.LAZY))
}
)
List<User> findUsersWithAccounts();

3.测试

在测试类UserTest中添加测试:

/**
 * 测试查询带有账户信息的用户信息
 * 延迟加载的方式
 */
@Test
public void testFindUsersWithAccounts(){
    List<User> users = userDao.findUsersWithAccounts();
    for (User user : users
    ) {
        System.out.println(user.getUserId());
        if(user.getUserId() == 41)
            System.out.println(user.getAccounts());
    }
}

一对多延迟加载

三、基于注解的二级缓存
1.开启二级缓存配置

1.在主配置文件SqlMapConfig.xml中添加二级缓存的支持

<setting name="cacheEnabled" value="true"/>

2.对应的接口开启二级缓存的支持

在接口IUserDao接口名的上方添加:

@CacheNamespace(blocking=true)  //mybatis 基于注解方式实现配置二级缓存
2.测试运行

在测试类UserTest中添加测试:

@Test
public void testL1Cache() {

    User user1 = userDao.findById(41);
    System.out.println("第一次查询的用户:" + user1);

    User user2 = userDao.findById(41);
    System.out.println("第二次查询用户:" + user2);
    System.out.print("第一次和第二次是否是同一对象:");
    System.out.println(user1 == user2);

    sqlSession.clearCache();//清空缓存
    User user3 = userDao.findById(41);
    System.out.println("第三次查询用户:" + user3);
    System.out.print("第二次和第三次是否是同一对象:");
    System.out.println(user2 == user3);

    sqlSession.close();//close操作会清空缓存
    //再次获取 SqlSession 对象
    sqlSession = factory.openSession();
    userDao = sqlSession.getMapper(IUserDao.class);
    User user4 = userDao.findById(41);
    System.out.println("第四次查询用户:" + user4);
    System.out.print("第三次和第四次是否是同一对象:");
    System.out.println(user3 == user4);

}

/**
 * 测试二级缓存
 */
@Test
public void testL2Cache() {

    User user1 = userDao.findById(41);
    System.out.println("第一次查询的用户:" + user1);
    sqlSession.close(); //关闭一级缓存

    sqlSession = factory.openSession();
    userDao = sqlSession .getMapper(IUserDao.class);
    User user2  = userDao .findById(41);
    System.out.println("第二次查询用户:" + user2);
    System.out.print("第一次和第二次是否是同一对象:");
    System.out.println(user1 == user2);

}
posted @ 2020-03-20 12:46  李一二  阅读(221)  评论(0编辑  收藏  举报