Mybatis之注解开发(七)

生活中,最使人疲惫的往往不是道路的遥远,而是心中的郁闷;最使人痛苦的往往不是生活的不幸,而是希望的破灭;最使人颓废的往往不是前途的坎坷,而是自信的丧失;最使人绝望的往往不是挫折的打击,而是心灵的死亡。所以我们要有自己的梦想,让梦想的星光指引着我们走出落漠,走出惆怅,带着我们走进自己的理想。

导读:本篇文章讲解 Mybatis之注解开发(七),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

一、引入依赖

<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.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>

二、添加jdbc与log配置

jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=chen
log4j.properties
log4j.rootCategory=debug, CONSOLE, LOGFILE

log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

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

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\mybatis.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


三、创建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>
    <!--配置别名-->
    <typeAliases>
        <package name="cn.ybzy.domain"></package>
    </typeAliases>
    <!-- 配置环境-->
    <environments default="mysql">
   		 <!-- 配置 mysql 的环境 -->
        <environment id="mysql">
       		 <!-- 配置事务的类型是 JDBC -->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射信息 -->
    <mappers>
        <!-- 配置dao接口的位置,有两种方式
				第一种:使用 mapper 标签配置 class 属性
				<mapper class="cn.ybzy.dao.IUserDao"></mapper>
				第二种:使用 package 标签,直接指定 dao 接口所在的包
				-->
		<package name="cn.ybzy.dao"/>
    </mappers>
</configuration>

四、Mybatis的常用注解

@Insert:实现新增

@Update:实现更新

@Delete:实现删除

@Select:实现查询

@Result:实现结果集封装

@Results:可以与@Result 一起使用,封装多个结果集

@ResultMap:实现引用@Results 定义的封装

@One:实现一对一结果集封装

@Many:实现一对多结果集封装

@SelectProvider: 实现动态 SQL 映射

@CacheNamespace:实现注解二级缓存的使用

五、基于注解实现基本的CRUD

1.创建User实体类

public class User implements Serializable{

    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;
}

2.创建IUserDao接口及方法

public interface IUserDao {

    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     */
    @Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
    void saveUser(User user);

    /**
     * 更新用户
     * @param user
     */
    @Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
    void updateUser(User user);

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

    /**
     * 根据id查询用户
     * @param userId
     * @return
     */
    @Select("select * from user  where id=#{id} ")
    User findById(Integer userId);

    /**
     * 根据用户名称模糊查询
     * @param username
     * @return
     */
    @Select("select * from user where username like #{username} ")
    List<User> findUserByName1(String username);

   /**
     * 根据用户名称模糊查询
     * @param username
     * @return
     */
    @Select("select * from user where username like '%${value}%' ")
    List<User> findUserByName2(String username);


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

3.执行测试

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 testSave(){
        User user = new User();
        user.setUsername("test save");
        user.setAddress("save address");

        userDao.saveUser(user);
    }

    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(44);
        user.setUsername("test  update");
        user.setAddress("update address");
        user.setSex("男");
        user.setBirthday(new Date());

        userDao.updateUser(user);
    }


    @Test
    public void testDelete(){
        userDao.deleteUser(44);
    }

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


    @Test
    public  void testFindByName1(){
        List<User> users = userDao.findUserByName("%update%");
        for(User user : users){
            System.out.println(user);
        }
    }

	   @Test
    public  void testFindByName2(){
        List<User> users = userDao.findUserByName("test");
        for(User user : users){
            System.out.println(user);
        }
    }
    
    @Test
    public  void testFindTotal(){
        int total = userDao.findTotalUser();
        System.out.println(total);
    }
}

4.修改User实体类

此时,实体类属性与数据库表的列名不一致,查询将出现无法正常封装结果集。
public class User implements Serializable {
	private Integer userId;
	private String userName;
	private Date userBirthday;
	private String userSex;
	private String userAddress;
}

5.修改IUserDao接口

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

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

   /**
	* 保存操作
	* @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);

}

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

实现复杂关系映射之前我们可以在映射文件中通过配置来实现,在使用注解开发时我们需要借助@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 注解(一对一)

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

@Many 注解(多对一)

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

使用格式:
	@Result(property="",column="",many=@Many(select=""))

七、注解实现一对一复杂关系映射及延迟加载

1.添加User及Account实体类

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

public class Account implements Serializable {
	private Integer id;
	private Integer uid;
	private Double money;
	//多对一关系映射:从表方应该包含一个主表方的对象引用
	private User user;
}

2.添加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(property = "user",column = "uid",one=@One(select="com.itheima.dao.IUserDao.findById",fetchType= FetchType.LAZY))
    })
    List<Account> findAll();
}

3.添加IUserDao接口并使用注解配置

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

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

4.测试一对一关联及延迟加载

@Test
    public  void  testFindAll(){
        List<Account> accounts = accountDao.findAll();
        //        for(Account account : accounts){
		//            System.out.println(account);
		//            System.out.println(account.getUser());
		//        }
    }

在这里插入图片描述

6.修改IAccountDao接口

修改IAccountDao接口查询为立即加载,fetchType= FetchType.EAGER
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(property = "user",column = "uid",one=@One(select="com.itheima.dao.IUserDao.findById",fetchType= FetchType.EAGER))
    })
    List<Account> findAll();
}

7.测试一对一关联及立即加载

@Test
    public  void  testFindAll(){
        List<Account> accounts = accountDao.findAll();
    }

在这里插入图片描述

八、注解实现一对多复杂关系映射及延迟加载

1.User 实体与Account实体

public class User implements Serializable {
	private Integer userId;
	private String userName;
	private Date userBirthday;
	private String userSex;
	private String userAddress;
	//一对多关系映射:主表方法应该包含一个从表方的集合引用
	private List<Account> accounts;
}

public class Account implements Serializable {

    private Integer id;
    private Integer uid;
    private Double money;
}

2.编写IUserDao接口并使用注解配置

@Many:
	相当于`<collection>`的配置
	select 属性:代表将要执行的 sql 语句
	fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值
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 = "address",property = "userAddress"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "birthday",property = "userBirthday"),
            @Result(property = "accounts",column = "id",
                    many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
                                fetchType = FetchType.LAZY))
    })
    List<User> findAll();
}

3.编写IAccountDao接口并使用注解配置

public interface IAccountDao {
    /**
     * 根据用户id查询账户信息
     * @param userId
     * @return
     */
    @Select("select * from account where uid = #{userId}")
    List<Account> findAccountByUid(Integer userId);
}

4.执行测试

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

在这里插入图片描述

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

在这里插入图片描述

九、基于注解的二级缓存

1.开启二级缓存

<!-- 配置二级缓存 -->
<settings>
	<!-- 开启二级缓存的支持 -->
	<setting name="cacheEnabled" value="true"/>
</settings>

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

//mybatis基于注解方式实现配置二级缓存
@CacheNamespace(blocking = true)
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 = "address",property = "userAddress"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "birthday",property = "userBirthday"),
            @Result(property = "accounts",column = "id",
                    many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
                                fetchType = FetchType.LAZY))
    })
    List<User> findAll();

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

3.测试使用二级缓存

 @Test
    public void testFindOne(){
        SqlSession session = factory.openSession();
        IUserDao userDao = session.getMapper(IUserDao.class);
        User user = userDao.findById(45);
        System.out.println(user);

        //清空一级缓存
        session.close();

        SqlSession session1 = factory.openSession();//再次打开session
        IUserDao userDao1 = session1.getMapper(IUserDao.class);
        User user1 = userDao1.findById(45);
        System.out.println(user1);


        session1.close();
    }

在这里插入图片描述

4.测试取消二级缓存配置

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137110.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!