Mybatis学习笔记之---CRUD(增删改查)

时间:2022-09-07 15:17:32

Mybatis的CRUD(增删改查)

Mybatis学习笔记之---CRUD(增删改查)

1.pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency> </dependencies>
2.SqlMapperConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPEconfiguration

        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>

                <property name="url" value="jdbc:mysql://localhost:3306/zml?useUnicode=true&amp;characterEncoding=utf-8"></property>

                <property name="username" value="root"></property>

                <property name="password" value="root"></property>

            </dataSource>

        </environment>

    </environments>

    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->

<mappers>

    <mapper resource="dao/UserDao.xml"></mapper>

</mappers>

</configuration>
3.Users.java
package entity;

public class Users {

    private int id;

    private String username;

    private String password;

    public int getId() {

        return id;

    }

    public void setId(int 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;

    }

    @Override

    public String toString() {

        return "Users{" +

                "id=" + id +

                ", username='" + username + '\'' +

                ", password='" + password + '\'' +

                '}';

    }

}
4.UserVo.java
package entity;

public class UserVo {

    private Users users;

    public Users getUsers() {

        return users;

    }

    public void setUsers(Users users) {

        this.users = users;

    }

}
5.UserDao.java
package dao;

        import entity.UserVo;

        import entity.Users;

        import java.util.List;

public interface UserDao {

     List<Users> findAll();

     Users find(int id);

     void save(Users users);

     void update(Users users);

     void delete(int id);

     List<Users> findVague(String name);

     int count();

     List<Users> findVo(UserVo vo);

}
6.UserDao.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPEmapper

        PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dao.UserDao">

    <!--查询所有-->

    <select id="findAll" resultType="entity.Users">

        select * from users

    </select>

    <!--根据ID查询-->

    <select id="find" resultType="entity.Users">

        select * from users where id=#{id}

    </select>

    <!--增加-->

    <insert id="save" parameterType="entity.Users">

        <!--查询新增用户的ID-->

       <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">

           select last_insert_id()

       </selectKey>

        insert into users(username,password) values(#{username},#{password})

    </insert>

    <!--根据ID进行修改-->

    <update id="update" parameterType="entity.Users">

        update users set username=#{username},password=#{password} where id=#{id}

    </update>

    <!--根据ID进行删除-->

    <delete id="delete" parameterType="entity.Users">

        delete from users where id=#{id}

    </delete>

    <!--模糊查询-->

    <select id="findVague" resultType="entity.Users">

--         select * from users where username like '%${value}%'

        select * from users where username like #{name}

    </select>

    <!--查询用户总数-->

    <select id="count" resultType="int">

        select count(id) from users

    </select>

    <!--将实体类封装到另一个实体类中的模糊查询-->

    <select id="findVo" resultType="entity.Users">

        select * from users where username like #{users.username}

    </select>

</mapper>
7.UserTest.java
package test;

import dao.UserDao;

import entity.UserVo;

import entity.Users;

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.List;

public class UserTest {

    private InputStream in;

    private SqlSession sqlSession;

    private UserDao UserDaoImpl;

    @Before

    public void init() throws IOException {

        //1.读取配置文件

        in= Resources.getResourceAsStream("SqlMapperConfig.xml");

        //2.创建SqlSessionFactory工厂

        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();

        SqlSessionFactory factory=builder.build(in);

        //3.使用工厂生产SqlSession对象

        sqlSession=factory.openSession();

        //4.使用SqlSession创建dao接口的代理对象

        UserDaoImpl=sqlSession.getMapper(UserDao.class);

    }

    @After

    public void destroy() throws IOException {

        //提交事务

        sqlSession.commit();

        //6.释放资源

        sqlSession.close();

        in.close();

    }

    /**

     * 查询所有

     * @throws IOException

     */

    @Test

    public void findall() throws IOException {

        //5.使用代理对象执行方法

        List<Users> users=UserDaoImpl.findAll();

        for(Users u:users){

            System.out.println(u);

        }

    }

    /**

     * 增加

     */

    @Test

    public void save(){

       Users users=new Users();

       users.setUsername("哈哈哈");

       users.setPassword("456");

       UserDaoImpl.save(users);

    }

    /**

     * 根据ID查询并修改

     */

    @Test

    public void update(){

        Users u=UserDaoImpl.find(15);

        u.setPassword("456");

        u.setUsername("小喵");

        UserDaoImpl.update(u);

    }

    /**

     * 根据id进行删除

     */

    @Test

    public void delete(){

        UserDaoImpl.delete(16);

    }

    /**

     * 模糊查询,查询所有名字中有小的用户

     * @throws IOException

     */

    @Test

    public void findVague() throws IOException {

        //5.使用代理对象执行方法

        List<Users> users=UserDaoImpl.findVague("%小%");

        for(Users u:users){

            System.out.println(u);

        }

    }

    /**

     * 查询用户总数

     */

    @Test

    public void count(){

        int c=UserDaoImpl.count();

        System.out.println(c);

    }

    /**

     * 将实体类封装到另一个实体类中的模糊查询

     */

    @Test

    public void findVo(){

        UserVo vo=new UserVo();

        Users users=new Users();

        users.setUsername("%小%");

        vo.setUsers(users);

        List<Users> list=UserDaoImpl.findVo(vo);

        for(Users u:list){

            System.out.println(u);

        }

    }

}