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

MyBatis的注解开发

程序员文章站 2022-06-02 15:23:48
...

单表的CRUD注解开发:

User实体类:

package com.zyb.pojo;

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

public class User implements Serializable {
private Integer id;
private String username;
private String sex;
private String address;
private Date birthday;

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", birthday=" + 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 getSex() {
        return sex;
    }

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

    public String getAddress() {
        return address;
    }

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

    public Date getBirthday() {
        return birthday;
    }

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

UserDao:

package com.zyb.dao;

import com.zyb.pojo.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;

public interface UserDao {
   @Select("select * from my_user")
    List<User> selAllUsers();

   @Insert("insert into my_user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday}) ")
   void saveUser(User u);

   @Update("update my_user set username=#{username} where id=#{id}")
   void updateUser(User user);

   @Delete("delete from my_user where id=#{id}")
   void deleteUserById(int userId);

   @Select("select * from my_user where id=#{id}")
   User selUserById(int userId);

   @Select("select * from my_user where username like '%${value}%'")
//   @Select("select * from my_user where username like #{username}")
   List<User> selUserByName(String userName);

    @Select("select count(*) from my_user")
    int usersNum();
}

 

测试:

package com.zyb.test;

import com.zyb.dao.UserDao;
import com.zyb.pojo.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 AnnotationCRUDTest {
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private UserDao userDao;

    @Before
    public  void init()throws Exception{
        in = Resources.getResourceAsStream("mybatis-config.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        userDao = session.getMapper(UserDao.class);
    }

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

    @Test
    public void testSelAllUsers(){
        List<User> users=userDao.selAllUsers();
        users.forEach(x-> System.out.println(x));
    }

    @Test
    public void testSaveUser(){
        User user= new User();
        user.setSex("男");
        user.setAddress("地球");
        user.setBirthday(new Date());
        user.setUsername("zhang");
        userDao.saveUser(user);
    }

    @Test
    public void testUpdateUser(){
       User user = new User();
       user.setId(58);
       user.setUsername("liu");
       user.setSex("女");
       userDao.updateUser(user);

    }

    @Test
    public void testDeleteUserById(){
        userDao.deleteUserById(58);
    }

    @Test
    public void testSelUserById(){
       User user= userDao.selUserById(52);
       System.out.println(user);
    }

    @Test
    public void testSelUserByName(){
        List<User> users=userDao.selUserByName("王");
        users.forEach(x-> System.out.println(x));
    }

    @Test
    public void testUsersNum(){
        int num=userDao.usersNum();
        System.out.println(num);
    }

}

 

多表注解操作:

逻辑:一个用户可以有多个账户,一个账户只能被一个用户拥有

User实体类多了一个:

MyBatis的注解开发

 

新增的Account实体类:

package com.zyb.pojo;

import java.io.Serializable;

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

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + 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;
    }

    public Account() {
    }
}

AccountDao:

package com.zyb.dao;

import com.zyb.pojo.Account;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface AccountDao {

    @Select("select * from my_account")
    @Results(id="accountMap",value = {
            @Result(property = "id",column = "id",id=true),
            @Result(property = "uid",column = "uid"),
            @Result(property = "money",column = "money"),
            @Result(property = "user",column = "uid",one = @One(select = "com.zyb.dao.UserDao.selUserById",fetchType= FetchType.EAGER))

    })
    List<Account> selAllAccounts2User();

    @Select("select * from my_account where uid=#{uid}")
    @ResultMap("accountMap")
    List<Account> selAccountsByUid();
}

UserDao:

package com.zyb.dao;

import com.zyb.pojo.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface UserDao {
   @Select("select * from my_user")
   @Results(id="userMap" ,value={
           @Result(property = "userId",column="id" ,id=true),
           @Result(property = "userName",column="username"),
           @Result(property = "userAddress",column="address"),
           @Result(property = "userSex",column="sex"),
           @Result(property = "userBirthday",column="birthday"),
           @Result(property = "accounts",column = "id",many = @Many(select = "com.zyb.dao.AccountDao.selAccountsByUid",fetchType = FetchType.LAZY))

   })
    List<User> selAllUsers();


   @Select("select * from my_user where id=#{id}")
   @ResultMap(value = {"userMap"})
   User selUserById(int userId);


   @Select("select * from my_user where username like #{username}")
   @ResultMap(value = {"userMap"})
   List<User> selUserByName(String userName);

}

Dao层分析:

Results点进去的源码:

id属性、Result类型的value数组

MyBatis的注解开发

 

 Result类型点进去的源码:

MyBatis的注解开发

One或Many点进去的源码:

MyBatis的注解开发

 

 注意在使用注解是mybatis-config.xml的配置

MyBatis的注解开发

相关标签: Mybatis-学习