Mybatis動態代理模式實現CRUD

項目實現的功能

查詢所有用戶信息
通過Id查詢用戶信息
添加用戶(回顯主鍵)
修改用戶信息
刪除用戶信息
通過用戶名字模糊查詢

一、引入依賴和工程結構

在這裏插入圖片描述

<?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.william</groupId>
    <artifactId>MybatisMapper</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <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.47</version>
        </dependency>
    </dependencies>

</project>

二、創建實體類

User

package com.william.domain;

import java.util.Date;

/**
 * @author :lijunxuan
 * @date :Created in 2019/7/9  19:28
 * @description :
 * @version: 1.0
 */
public class User {
    private  Integer id;
    private String username;
    private String password;
    private String  sex;
    private Date birthday;

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

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

}

三、映射文件

1.UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.william.dao.UserMapper">
    <!--查詢所有用戶信息-->
    <select id="findAll" resultType="com.william.domain.User">
        select * from user
    </select>
    <!--通過ID查詢用戶信息-->
    <select id="findById" parameterType="java.lang.Integer" resultType="com.william.domain.User">
        select * from user where id=#{id}
    </select>
    <!--模糊查詢-->
    <select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">
        select * from user where username like "%"#{value}"%"
    </select>
    <!--增加用戶信息-->
    <insert id="insert" parameterType="com.william.domain.User">
        <selectKey resultType="java.lang.Integer" keyColumn="id" keyProperty="id" order="AFTER" >
              select last_insert_id()
        </selectKey>
        insert into user values (null ,#{username},#{password},#{sex},#{birthday})
    </insert>
    <!--更新用戶信息-->
    <update id="update" parameterType="com.william.domain.User">
        update  user set username=#{username},password=#{password},sex=#{sex},birthday=#{birthday} where id=#{id}
    </update>
    <!--刪除用戶信息-->
    <delete id="delete" parameterType="java.lang.Integer">
        delete  from user where id =#{id}
    </delete>
</mapper>

四、引入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, info

# 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:\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


五、測試類

TestCrud

package com.william;

import com.william.dao.UserMapper;
import com.william.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.Test;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author :lijunxuan
 * @date :Created in 2019/7/12  10:16
 * @description :
 * @version: 1.0
 */
public class TestCrud {
    /**
     * 查詢所有用戶信息
     * @throws IOException
     */
    @Test
    public void findAll() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取某接口的動態代理對象(獲取某接口的一個實現類)
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
           sqlSession.close();
    }

    /**
     *
     *通過Id查詢用戶信息
     * @throws IOException
     */
    @Test
    public void findById() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取某接口的動態代理對象(獲取某接口的一個實現類)
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User findByIdUser = userMapper.findById(43);
        System.out.println(findByIdUser);
        sqlSession.close();
    }

    /**
     * 模糊查詢
     * 通過用戶名模糊查詢
     * @throws IOException
     */
    @Test
    public void findByUsername() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取某接口的動態代理對象(獲取某接口的一個實現類)
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> findByIdUsernameList = userMapper.findByUsername("a");
        for (User user : findByIdUsernameList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    /**
     * 增加用戶信息
     * @throws IOException
     */
    @Test
    public void  insert() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取某接口的動態代理對象(獲取某接口的一個實現類)
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user= new User();
        user.setUsername("today");
        user.setPassword("hello");
        user.setSex("女");
        userMapper. insert(user);
        //事務提交
        sqlSession.commit();
        System.out.println("添加後用戶的id爲:"+user.getId());
        sqlSession.close();
    }

    /**
     * 更新用戶信息
     * @throws IOException
     */
    @Test
    public void  update() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取某接口的動態代理對象(獲取某接口的一個實現類)
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user= new User();
        user.setId(45);
        user.setUsername("today");
        user.setPassword("hello");
        user.setSex("女");
        userMapper. update(user);
        //事務提交
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 通過id刪除用戶信息
     * @throws IOException
     */
    @Test
    public void  delete() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //獲取某接口的動態代理對象(獲取某接口的一個實現類)
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper. delete(50);
        //事務提交
        sqlSession.commit();
        sqlSession.close();
    }
}

【重點】mybatis動態代理模式開發的要求

1.dao接口和映射文件必須路徑相同,文件名相同(dao接口和映射文件必須在同一個文件夾中,文件名必須相同)

如圖所示:
在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述

2.namespace必須是 接口的全限定類名

在這裏插入圖片描述

3.映射文件中的id值必須是接口的方法名

在這裏插入圖片描述

4.參數類型和返回值類也必須是匹配的

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章