Mybatis注解开发-2020.03.25

mybatis注解开发的环境搭建

  • pom.xml and SqlMapConfig.xml
   <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.itheima</groupId>
   <artifactId>day04_eesy_03annotation_mybatis</artifactId>
   <version>1.0-SNAPSHOT</version>
   <packaging>jar</packaging>

   <dependencies>
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.4.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.12</version>
       </dependency>
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.10</version>
       </dependency>
   </dependencies>
</project>


<?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="com.itheima.domain"></package>
   </typeAliases>
   <!-- 配置环境-->
   <environments default="mysql">
       <environment id="mysql">
           <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>
   <!-- 指定带有注解的dao接口所在位置 -->
   <mappers>
       <mapper class="com.itheima.dao.IUserDao"></mapper>
   </mappers>
</configuration>
  • User.java and IUserDao.java
   package com.itheima.domain;

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

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public class User implements Serializable{

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

   public Integer getId() {
       return id;
   }

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

   public String getUsername() {
       return username;
   }

   public void setUsername(String username) {
       this.username = username;
   }

   public String getAddress() {
       return address;
   }

   public void setAddress(String address) {
       this.address = address;
   }

   public String getSex() {
       return sex;
   }

   public void setSex(String sex) {
       this.sex = sex;
   }

   public Date getBirthday() {
       return birthday;
   }

   public void setBirthday(Date birthday) {
       this.birthday = birthday;
   }

   @Override
   public String toString() {
       return "User{" +
               "id=" + id +
               ", username='" + username + '\'' +
               ", address='" + address + '\'' +
               ", sex='" + sex + '\'' +
               ", birthday=" + birthday +
               '}';
   }
}


package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 在mybatis中针对,CRUD一共有四个注解
*  @Select @Insert @Update @Delete
*/
public interface IUserDao {

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

mybatis注解开发测试和使用注意事项

  • MybatisAnnoTest.java
    package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.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 java.io.InputStream;
import java.util.List;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public class MybatisAnnoTest {

   /**
    * 测试基于注解的mybatis使用
    * @param args
    */
   public static void main(String[] args) throws  Exception{
       //1.获取字节输入流
       InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
       //2.根据字节输入流构建SqlSessionFactory
       SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
       //3.根据SqlSessionFactory生产一个SqlSession
       SqlSession session = factory.openSession();
       //4.使用SqlSession获取Dao的代理对象
       IUserDao userDao = session.getMapper(IUserDao.class);
       //5.执行Dao的方法
       List<User> users = userDao.findAll();
       for(User user : users){
           System.out.println(user);
       }
       //6.释放资源
       session.close();
       in.close();
   }
}

mybatis注解开发保存和更新功能

  • IuserDao.java
  package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 在mybatis中针对,CRUD一共有四个注解
*  @Select @Insert @Update @Delete
*/
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);

  
}

  • AnnotationCRUDTest.java
    package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.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;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
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("mybatis annotation");
       user.setAddress("北京市昌平区");

       userDao.saveUser(user);
   }

   @Test
   public void testUpdate(){
       User user = new User();
       user.setId(57);
       user.setUsername("mybatis annotation update");
       user.setAddress("北京市海淀区");
       user.setSex("男");
       user.setBirthday(new Date());

       userDao.updateUser(user);
   }

}

mybatis注解开发CRUD和其他操作

  • IuserDao.java
     /**
    * 删除用户
    * @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} ")
   @Select("select * from user where username like '%${value}%' ")
   List<User> findUserByName(String username);

   /**
    * 查询总用户数量
    * @return
    */
   @Select("select count(*) from user ")
   int findTotalUser();
  • AnnotationCRUDTest.java
   @Test
   public void testDelete(){
       userDao.deleteUser(51);
   }

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


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

   @Test
   public  void testFindTotal(){
       int total = userDao.findTotalUser();
       System.out.println(total);
   }

mybatis注解建立实体类属性和数据库表中列的对应关系

  • User.java
  package com.itheima.domain;

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

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public class User implements Serializable{

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


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

  • IUserDao.java
  package com.itheima.dao;

import com.itheima.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 在mybatis中针对,CRUD一共有四个注解
*  @Select @Insert @Update @Delete
*/
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 username
    * @return
    */
   @Select("select * from user where username like #{username} ")
   @ResultMap("userMap")
   List<User> findUserByName(String username);


}

mybatis注解开发一对一的查询配置

  • Account.java
 package com.itheima.domain;

import java.io.Serializable;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
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 +
               '}';
   }
}

  • IAccountDao.java
  package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
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();

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

mybatis注解开发一对多的查询配置

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

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

   public void setAccounts(List<Account> accounts) {
       this.accounts = accounts;
   }
  • IUserDao.java
      /**
    * 查询所有用户
    * @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();
  • IAccountDao.java
  package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
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();

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

  • AnnotationCRUDTest.java
  package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.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.List;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
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("---每个用户的信息----");
//            System.out.println(user);
//            System.out.println(user.getAccounts());
//        }
   }

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


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


}

mybatis注解开发使用二级缓存

  • SecondLevelCatchTest.java
   package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.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;

/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public class SecondLevelCatchTest {

   private InputStream in;
   private SqlSessionFactory factory;


   @Before
   public  void init()throws Exception{
       in = Resources.getResourceAsStream("SqlMapConfig.xml");
       factory = new SqlSessionFactoryBuilder().build(in);

   }

   @After
   public  void destroy()throws  Exception{

       in.close();
   }

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

       session.close();//释放一级缓存

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


       session1.close();

   }
}

  • IUserDao.java and SqlMapConfig.xml
 @CacheNamespace(blocking = true)
 public interface IUserDao {
    ***
 }



  <!--配置开启二级缓存-->
   <settings>
       <setting name="cacheEnabled" value="true"/>
   </settings>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,884评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,755评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,369评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,799评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,910评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,096评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,159评论 3 411
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,917评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,360评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,673评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,814评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,509评论 4 334
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,156评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,882评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,123评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,641评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,728评论 2 351

推荐阅读更多精彩内容

  • 1.Mybatis 延迟加载策略 问题:在一对多中,当我们有一个用户,该用户有100个账户, ①在查询用户的时候,...
    奖励自己学习一小时python阅读 540评论 0 1
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,465评论 0 4
  • 延迟加载和立即加载的概念 问题 :在一对多中,我们需要一个用户,他有100个账户在查询用户的时候,要不要把关联的账...
    Deanfluenza01阅读 188评论 0 0
  • 1.MyBatis简述 mybatis是一个优秀的基于 java 的持久层框架,它内部封装了 jdbc,使开发者只...
    测试员阅读 23,147评论 1 18
  • “我在人民广场吃着炸鸡,而此时此刻你在哪里?” “你在人民广场吃着炸鸡?我在中山路口等公交!” 没错,我堆砌这...
    陆星渊阅读 453评论 0 1