转载

Mybatis基于注解方式的多表(CRUD)操作

  • 基于注解方式实现的多对多增删改查操作(一对多原理类似)
  • 基于注解方式实现的多对一增删改查操作(mybatis默认多对一为 一对一)

pom.xml中导入mybatis项目依赖坐标

<?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.baoji.mybatis</groupId>
    <artifactId>mybatis_03_zhujie</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <!-- 配置mybatis所依赖的jar包 -->
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</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.baoji.mybatis.entity"/>
    </typeAliases>
    <!-- 配置环境 -->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置注解所对应的dao接口映射文件 -->
    <mappers>
        <package name="com.baoji.mybatis.dao"/>
    </mappers>
</configuration>
复制代码

第二步(配置jdbcConfig.xml配置文件)

jdbcConfig.xml
复制代码
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_user? useUnicode = true&characterEncoding = utf-8
username=root
password=root
复制代码

第三步(配置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=d:xis.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
复制代码

第四步(配置实体类)

User.java
     //一对多:一个用户下的所有账户信息
    private List<Account> accounts;

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

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }
复制代码
package com.baoji.mybatis.entity;

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

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 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 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 + '/'' +
                '}';
    }
}
复制代码
Account.java
    /*
         多对一:(Mybatis中默认多对一为一对一)
         配置多对一关系封装的User信息
     */
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
复制代码
package com.baoji.mybatis.entity;

import java.io.Serializable;

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

    /*
         多对一:(Mybatis中默认多对一为一对一)
         配置多对一关系封装的User信息
     */
    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 String getMoney() {
        return money;
    }

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

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

第五步(配置dao接口)

IUserDao.java
复制代码
package com.baoji.mybatis.dao;

import com.baoji.mybatis.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface IUserDao {
    /**
     * 查询所有用户
     * Mybatis中操作CRUD共有4个注解、
        @Select @Insert @Delete @Update
     */

    //配置实体类中属性与数据库字段名不一致问题(id默认为false,如果为主键,设置为true即可)
    @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"),
            /*
                配置封装的集合对象的映射关系
                    select : 指想要执行的具体接口中方法
                    fetchType : 延迟加载类型
                         LAZY :延时加载  (一般适应于多对多和一对多)
                         EAGER :立即加载 (一般适用于一对一和多对一)
                         fetchType = FetchType.EAGER
             */
                @Result(column = "id",property = "accounts",many = @Many(select = "com.baoji.mybatis.dao.IAccountDao.findById",fetchType = FetchType.LAZY)),
    })
   // @ResultMap("userMap")
    //@ResultMap(value = {"userMap"})//标准写法
    List<User> findAll();

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

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

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

    /**
     * 根据用于id查询信息
     */
    @Select("select * from user where id = #{id}")
    @ResultMap("userMap")
    User selectById(Integer id);

    /**
     * 根据用户名模糊查询用户信息
     */
    @Select("select * from user where username like #{username}")
    @ResultMap("userMap")
    List<User> selectByName(String username);

    /**
     * 查询总记录数
     */
//    @Select("select count(*) from user")
//    @ResultMap("userMap")
//    int findAccount();
}
复制代码
IAccount.java
复制代码
package com.baoji.mybatis.dao;

import com.baoji.mybatis.entity.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;

public interface IAccountDao {
    /**
     * 查询所有账号,通过账号查询用户信息
     * @return
     */

    //使用注解配置账户的映射关系
    @Results(value = {
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "uid",column = "uid"),
            @Result(property = "money",column = "money"),
            /*
                配置封装的对象的映射关系
                    select : 指想要执行的具体接口中方法
                    fetchType : 延迟加载类型
                         LAZY :延时加载  (一般适应于多对多和一对多)
                         EAGER :立即加载 (一般适用于一对一和多对一)
                         fetchType = FetchType.EAGER
             */
            @Result(property = "user",column = "uid",one = @One(select = "com.baoji.mybatis.dao.IUserDao.selectById",fetchType = FetchType.EAGER)),
    })
    @Select("select * from account")
    List<Account> findAll();

    @Select("select * from account where uid = #{userId}")
    List<Account> findById(Integer uid);
}
复制代码

第六步(编写测试类)

IUserTest.java
复制代码
package com.baoji.mybatis.test;

import com.baoji.mybatis.dao.IUserDao;
import com.baoji.mybatis.entity.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.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class IUserTest {
        private InputStream in;
        private SqlSessionFactory factory;
        private SqlSession sqlSession;
        private IUserDao userDao;
        @Before  //测试方法之前执行
        public void init() throws IOException {
            //1、获取字符输入流加载配置文件
            in = Resources.getResourceAsStream("Config.xml");
            //2、通过字节输入流创建工厂对象
            factory = new SqlSessionFactoryBuilder().build(in);
            //3、通过工厂对象创建sqlSession对象
            sqlSession = factory.openSession();
            //4、通过sqlSession创建dao代理对象
            userDao = sqlSession.getMapper(IUserDao.class);
        }
        @After  //测试方法之后执行
        public void destory() throws IOException {
            //提交事务
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
            in.close();
        }
        //查询所有用户信息
        @Test
        public void testFindAll() {
            //5、使用代理对象执行操作
            List<User> list = userDao.findAll();
            for (User users : list) {
                System.out.println("每个用户的信息");
                System.out.println(users);
                System.out.println(users.getAccounts());
            }
        }
        //添加用户信息
        @Test
        public void testSave(){
            User user = new User();
            user.setUserName("李四");
            user.setUserBirthday(new Date());
            user.setUserSex("男");
            user.setUserAddress("陕西宝鸡");
            userDao.saveUser(user);
        }
        //删除所有用户信息
        @Test
    public void testDelete(){
        userDao.deleteUser(60);
        }
        //修改用户信息
    @Test
    public void testUpdate(){
        User user = new User();
        user.setUserName("lisi");
        user.setUserBirthday(new Date());
        user.setUserSex("女");
        user.setUserAddress("陕西宝鸡");
        user.setUserId(51);
        userDao.updateUser(user);
    }
    @Test
    //根据id查询用户信息
    public void testFindById(){
        User user = userDao.selectById(42);
        System.out.println(user);
    }
    @Test
    //根据姓名模糊查询
    public void testFindByName(){
            List<User> list = userDao.selectByName("%王%");
            for(User users:list){
                System.out.println(users);
            }
    }
//    @Test
    //查询总记录条数
//    public void testFindAccount(){
//            int count = userDao.findAccount();
//        System.out.println(count);
//    }
}
复制代码
IAccount.java
复制代码
package com.baoji.mybatis.test;

import com.baoji.mybatis.dao.IAccountDao;
import com.baoji.mybatis.dao.IUserDao;
import com.baoji.mybatis.entity.Account;
import com.baoji.mybatis.entity.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.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class IAccountTest {
        private InputStream in;
        private SqlSessionFactory factory;
        private SqlSession sqlSession;
        private IAccountDao accountDao;
        @Before  //测试方法之前执行
        public void init() throws IOException {
            //1、获取字符输入流加载配置文件
            in = Resources.getResourceAsStream("Config.xml");
            //2、通过字节输入流创建工厂对象
            factory = new SqlSessionFactoryBuilder().build(in);
            //3、通过工厂对象创建sqlSession对象
            sqlSession = factory.openSession();
            //4、通过sqlSession创建dao代理对象
            accountDao = sqlSession.getMapper(IAccountDao.class);
        }
        @After  //测试方法之后执行
        public void destory() throws IOException {
            //提交事务
            sqlSession.commit();
            //关闭资源
            sqlSession.close();
            in.close();
        }
        //查询所有账号信息
    @Test
        public void Test(){
            List<Account> list = accountDao.findAll();
            for(Account accounts:list){
                System.out.println("每个账户的信息");
                System.out.println(accounts);
                System.out.println(accounts.getUser());
            }
        }
}
复制代码

注解比xml方式更加简便,底层封装了xml的配置方式

原文  https://juejin.im/post/5dc6acc75188255927494bc0
正文到此结束
Loading...