Mybatis的CRUD操作【包含查询记录总条数、模糊查找】(完整代码演示)

Mybatis的CRUD操作

目录结构

在这里插入图片描述

完整代码

pom.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.keafmd</groupId>
    <artifactId>day02_eesy_01mybatisCRUD</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <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.49</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>
            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

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

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">
<!--mybatis的主配置文件-->
<configuration>
    <!--配置环境-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!--配置连接数据库的4个基本信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="18044229"/>
            </dataSource>
        </environment>
    </environments>

    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件
        如果是用注解,此处应该用class属性指定被注解的dao全限定类名
    -->
    <mappers>
        <mapper resource="com/keafmd/dao/IUserDao.xml"></mapper>
        <!--<mapper class="com.keafmd.dao.IUserDao"></mapper>-->
    </mappers>


</configuration>

User:

package com.keafmd.domain;

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

/**
 * Keafmd
 *
 * @ClassName: User
 * @Description:
 * @author: 牛哄哄的柯南
 * @date: 2021-02-08 15:16
 */
public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    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 Date getBirthday() {
        return birthday;
    }

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

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

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

IUserDao:

package com.keafmd.dao;

import com.keafmd.domain.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: IUserDao
 * @Description: 用户的持久层接口
 * @author: 牛哄哄的柯南
 * @date: 2021-02-06 19:29
 */

public interface IUserDao {
    /**
     * 查询所有操作
     * @return
     */
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     */
    void saveUser(User user);

    /**
     * 更新用户
     * @param user
     */
    void updateUser(User user);

    /**
     * 根据id删除用户
     * @param id
     */
    void deleteUser(Integer id);

    /**
     * 根据id查新用户信息
     * @param id
     * @return
     */
    User findById(Integer id);

    /**
     * 根据名称模糊查询
     * @param username
     * @return
     */
    List<User> findByName(String username);

    /**
     * 查询总用户数
     * @return
     */
    int findTotal();

}

IUserDao.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.keafmd.dao.IUserDao">
    <!--配置查询所有-->
    <!--id为方法名称-->
    <select id="findAll" resultType="com.keafmd.domain.User">
        select * from user
    </select>

    <!--保存用户-->
    <insert id="saveUser" parameterType="com.keafmd.domain.User">
        <!--配置插入操作后,获取插入的id-->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday});
    </insert>

    <!--更新用户-->
    <update id="updateUser" parameterType="com.keafmd.domain.User">
        update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
    </update>

    <!--删除用户-->
    <!--#{id}这里面写个占位符就行-->
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id = #{uid}
    </delete>

    <!--根据id查询用户-->
    <select id="findById" parameterType="Integer" resultType="com.keafmd.domain.User">
        select * from user where id = #{id}
    </select>

    <!--根据名称模糊查询-->
    <select id="findByName" parameterType="String" resultType="com.keafmd.domain.User">
        <!--select * from user where username like #{name}-->
        <!--value是固定的,源码写固定了,这种了解即可,不推荐-->
        select * from user where username like '%${value}%'
    </select>

    <!--查询总用户数-->
    <select id="findTotal" resultType="int">
        select count(id) from user;
    </select>

</mapper>

测试代码:

package com.keafmd.test;

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

/**
 * Keafmd
 *
 * @ClassName: MybatisTest
 * @Description: 测试类,测试crud操作
 * @author: 牛哄哄的柯南
 * @date: 2021-02-08 15:24
 */
public class MybatisTest {

    private InputStream in;
    private SqlSession sqlsession;
    private IUserDao userDao;

    @Before // 用于在测试方法执行前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        sqlsession = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        userDao = sqlsession.getMapper(IUserDao.class);
    }

    @After // 用于在测试方法执行后执行
    public void destory() throws Exception{
        //提交事务
        sqlsession.commit();
        //6.释放资源
        sqlsession.close();
        in.close();
    }

    /**
     * 查询所有
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {

        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }

    }

    /**
     * 测试保存操作
     */
    @Test
    public void testSave() throws Exception {
        User user = new User();
        user.setUsername("Keafmd laset insertid");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("XXXXXXX");
        System.out.println("保存操作前:"+user);
        //5.执行保存方法
        userDao.saveUser(user);
        System.out.println("保存操作后:"+user);
    }

    /**
     * 测试更新
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception {
        User user = new User();
        user.setId(42);
        user.setUsername("update");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setAddress("XXXXXXX");
        //5.执行更新方法
        userDao.updateUser(user);
    }

    /**
     * 测试删除
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception {
        //5.执行删除方法
        userDao.deleteUser(48);
    }

    /**
     * 查询一个
     * @throws Exception
     */
    @Test
    public void testFindOne() throws Exception {
        //5.执行查询一个方法
        User user = userDao.findById(50);
        System.out.println(user);
    }

    /**
     * 根据username模糊查询
     * @throws Exception
     */
    @Test
    public void testFindByName() throws Exception {
        //5.执行模糊查询方法
        /*List<User> users = userDao.findByName("%王%");*/
        List<User> users = userDao.findByName("王");
        for (User user : users) {
            System.out.println(user);
        }
    }

    /**
     * 查询记录总条数
     * @throws Exception
     */
    @Test
    public void testFindTiotal() throws Exception {
        //5.执行记录总条数
        int total = userDao.findTotal();
        System.out.println(total);
    }

}

以上就是Mybatis的CRUD操作【包含查询记录总条数、模糊查找】(完整代码演示)的全部内容。

看完如果对你有帮助,感谢点赞支持!
如果你是电脑端的话,看到右下角的 “一键三连” 了吗,没错点它[哈哈]

在这里插入图片描述

加油!

共同努力!

Keafmd

相关推荐
©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页