MyBatis learning summary (two): the CRUD operation of MyBatis

1. XML-based CRUD operations

Earlier, we realized the query of all data in the database in the entry program. Next, based on the entry program, CRUD of database data is realized.

(1) Modify IUserdao and add method.

public interface IUserDao {
    /**
     * 增加用户
     */
    void addUser(User user);
    /**
     * 删除用户
     */
    void deleteById(Integer id);
    /**
     * 修改用户
     */
    void updateUser(User user);
    /**
     * 查询所有
     * @return
     */
    List<User> findAll();

}

(2) Add sql statement in 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">
<!--namespace:指定了唯一的命名空间-->
<mapper namespace="com.day1.dao.IUserDao">
    <!--  添加用户  -->
    <insert id="addUser" parameterType="com.day1.entity.User">
        insert into t_user(username, password) values(#{username}, #{password});
    </insert>
    <!--  删除用户  -->
    <delete id="deleteById" parameterType="int">
        delete from t_user where id = #{id}
    </delete>
    <!--  更新用户信息  -->
    <update id="updateUser" parameterType="com.day1.entity.User">
        update t_user set username =#{username}, password= #{password} where id = #{id}
    </update>
    <!--
        查询所有用户
      -->
    <select id="findAll" resultType="com.day1.entity.User">
        select * from t_user;
    </select>
</mapper>

(3) Create a test class CRUDTest.

 

public class CRUDTest {
    InputStream in = null;
    SqlSessionFactoryBuilder builder = null;
    SqlSessionFactory factory = null;
    SqlSession sqlSession = null;
    IUserDao userDao = null;

    @Before
    public void init() throws IOException {
        //1、读取配置文件
        in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        builder = new SqlSessionFactoryBuilder();
        factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        sqlSession = factory.openSession();
        userDao = sqlSession.getMapper(IUserDao.class);
    }
    @After
    public void destory() throws IOException {
        sqlSession.commit();
        sqlSession.close();
        in.close();
    }

    @Test
    public void testInsert(){
        User user = new User("宋江", "song123");
        userDao.addUser(user);
    }

    @Test
    public void testDelete(){
        userDao.deleteById(5);
    }

    @Test
    public void testUpdate(){
        User user = new User(5,"宋江", "song123");
        userDao.updateUser(user);
    }

    @Test
    public void testFindAll(){
        List<User> userList = userDao.findAll();
        for(User user : userList){
            System.out.println(user);
        }
    }
}

 Test increase data operation:

Test query all, as follows: 

 Test the data modification operation, as follows:

 Test delete data, as follows:

 

There is another XML-based implementation method, which is to complete CRUD based on the interface implementation class. This method is enough to understand, because if this method is used in actual development, it will increase the complexity of development and the amount of code. Here can demonstrate its use:

(1) Add the implementation class UserDaoImpl of IUserDao.

public class UserDaoImpl implements IUserDao {
    private SqlSessionFactory factory;

   public UserDaoImpl(SqlSessionFactory factory) {
       this.factory = factory;
   }
    @Override
    public void addUser(User user) {
        SqlSession sqlSession = factory.openSession();
        sqlSession.insert("com.day1.dao.IUserDao.addUser", user);
    }

    @Override
    public void deleteById(Integer id) {
        SqlSession sqlSession = factory.openSession();
        sqlSession.delete("com.day1.dao.IUserDao.deleteById", id);
    }

    @Override
    public void updateUser(User user) {
        SqlSession sqlSession = factory.openSession();
        sqlSession.update("com.day1.dao.IUserDao.updateUser", user);
    }

    @Override
    public List<User> findAll() {
       SqlSession sqlSession = factory.openSession();
       List<User> list = sqlSession.selectList("com.day1.dao.IUserDao.findAll");
       return list;
    }
}

(2) Create the test class ImplTest.

public class ImplTest {
    InputStream in = null;
    SqlSessionFactoryBuilder builder = null;
    SqlSessionFactory factory = null;
    IUserDao userDao = null;

    @Before
    public void init() throws IOException {
        //1、读取配置文件
        in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        builder = new SqlSessionFactoryBuilder();
        factory = builder.build(in);
        //3、使用IUserDao创建对象
        userDao = new UserDaoImpl(factory);
    }
    @After
    public void destory() throws IOException {
        in.close();
    }

    @Test
    public void testFindAll(){
        System.out.println(userDao.findAll());
    }

    @Test
    public void testInsert(){
       User user = new User("吴用","aabbcc");
       userDao.addUser(user);
    }

    @Test
    public void testUpdate(){
        User user = new User(6, "吴用","123123");
        userDao.updateUser(user);
    }


    @Test
    public void testDelete(){
        userDao.deleteById(6);
    }




}

Two, annotation-based CRUD operations

 If CRUD is implemented based on annotations, the existence of userMapper files is not required.

(1) Configure the interface class in SqlMapperConfig.xml.

    <mappers>
        <mapper class="com.day1.dao.IUserDao"></mapper>
    </mappers>

(2) Modify the interface class

public interface IUserDao {
    /**
     * 增加用户
     */
    @Insert("insert into t_user(username, password) values(#{username}, #{password});")
    void addUser(User user);
    /**
     * 删除用户
     */
    @Delete("delete from t_user where id = #{id}")
    void deleteById(Integer id);
    /**
     * 修改用户
     */
    @Update("update t_user set username=#{username}, password=#{password} where id = #{id}")
    void updateUser(User user);
    /**
     * 查询所有
     * @return
     */
    @Select("select * from t_user")
    List<User> findAll();

}

(3) Create a test class

public class AnnoTest {
    InputStream in = null;
    SqlSessionFactoryBuilder builder = null;
    SqlSessionFactory factory = null;
    SqlSession sqlSession = null;
    IUserDao userDao =null;

    @Before
    public void init() throws IOException {
        //1、读取配置文件
        in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        builder = new SqlSessionFactoryBuilder();
        factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        sqlSession = factory.openSession();
        userDao = sqlSession.getMapper(IUserDao.class);
    }
    @After
    public void destory() throws IOException {
        sqlSession.commit();
        sqlSession.close();
        in.close();
    }
    @Test
    public void testFindAll(){
        System.out.println(userDao.findAll());
    }

    @Test
    public void testInsert(){
        User user = new User("吴用","aabbcc");
        userDao.addUser(user);
    }

    @Test
    public void testUpdate(){
        User user = new User(6, "吴用","123123");
        userDao.updateUser(user);
    }


    @Test
    public void testDelete(){
        userDao.deleteById(6);
    }

}

Three, other operations on the data

The previous two parts introduced the implementation based on XML and annotations respectively, and then the database operations will be completed in XML.

1. Query a piece of data

(1) Add the findById(Integer id) method in IUserDao.

    /**
     * 根据id查询用户
     */
    User findById(Integer id);

(2) Add a query method in userMapper.xml.

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

(3) Add a test method to the test class.

    @Test
    public void testFindById(){
        User user = userDao.findById(3);
        System.out.println(user);
    }

The execution results are as follows:

2. Fuzzy query

In order to realize the fuzzy query, several pieces of data will be inserted into the t_user table. as follows:

insert into t_user(username,password) values("张飞","zahngfei");
insert into t_user(username,password) values("张倩","zhangabc");
insert into t_user(username,password) values("张超","1231233");

There are two ways of fuzzy query, one is to splice% when passing parameters, and the content of the SQL statement remains unchanged; the other way is to add% to the SQL statement, that is, ${%value%}.

(1) Method 1: Use #{}

This method needs to add% in front of the parameter when passing in the parameter, but there is no need to add it in the mapper file, which is equivalent to PreparedStatement, as follows:

select * from t_user where username like #{para};

userDao.findUser("%para%")

The first step: add a method in IUserDao

    /**
     * 模糊查询方式一
     */
    List<User> findLikeUser01(String name);

Step 2: Add sql statement in userMapper.xml.

<!-- 模糊查询方式一  -->
    <select id="findLikeUser01" parameterType="String" resultType="com.day1.entity.User">
        select * from t_user where username like #{username}
    </select>

The third step: test.

    @Test
    public void testFindLike01(){
        List<User> userList = userDao.findLikeUser01("%张%");
        for(User user : userList){
            System.out.println(user);
        }
    }

(2) Method 2: Use ${}

In this way, you need to add% to the statement, but you don't need to add% when passing parameters. The essence is that the bottom layer does a splicing operation, which is equivalent to Statement. as follows:

select * from t_user where username like ${'%para%'}

userDao.findUser("para")

The first step: add a method in IUserDao


    /**
     * 模糊查询方式二
     */
    List<User> findLikeUser02(String name);

Step 2: Add sql statement in userMapper.xml.

    <!-- 模糊查询方式二  -->
    <select id="findLikeUser02" parameterType="String" resultType="com.day1.entity.User">
        select * from t_user where username like '%${value}%'
    </select>

The third step: test.

    @Test
    public void testFindLike02(){
        List<User> userList = userDao.findLikeUser02("张");
        for(User user : userList){
            System.out.println(user);
        }
    }

(3) Explanation of two ways

The first way, its console output statement is like this:

 In the previous implementation process, you can see that% is not added to the configuration file as the condition of the fuzzy query, so when the string argument is passed in, the identifier% of the fuzzy query needs to be given. The #{username} in the configuration file acts as a placeholder, so the SQL statement is displayed as "?".

The second way, its console output statement is like this:

In this way, there is no need to add the fuzzy query matching symbol% ​​in the program code, and the SQL statement is equivalent to a stringing operation.

(4) The difference between #{} and ${}

#{} represents a placeholder symbol, through #{} can achieve preparedStatement to set the value in the placeholder, automatic java type and jdbc type conversion, #{} can effectively prevent sql injection. #{}Can receive simple type values ​​or pojo attribute values. If parameterType transmits a single simple type value, #{} brackets can be value or other names, and its content is not limited.
${} means splicing sql strings, through ${}, the content passed in parameterType can be spliced ​​in sql without jdbc type conversion, ${} can receive simple type values ​​or pojo attribute values, if parameterType transmits a single simple type value , ${} can only be value in parentheses. The source code is as follows:

3. Get the id of the saved data

When inserting a record into a database table whose primary key is self-incrementing, if you want to get the id of the record just written, you need to use the select last_insert_id(); statement to get the auto-increment id returned after inserting the record value. Use as follows:

(1) Modify the insert statement in userMapper.xml

    <!--  添加用户  -->
    <insert id="addUser" parameterType="com.day1.entity.User">
        <!--
        keyProperty:将查询到主键值设置到 parameterType 指定的对象的那个属性
        keyColumn:数据库中的列名
        order:SELECT LAST_INSERT_ID() 执行顺序,相对于 insert 语句来说它的执行顺序
        resultType:指定 SELECTLAST_INSERT_ID() 的结果类型
         -->
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into t_user(username, password) values(#{username}, #{password});
    </insert>

Parameter Description:

keyProperty: Which property of the object specified by parameterType will be queried to set the primary key value.

keyColumn: The column name in the database.

order: select last_insert_id() execution order, relative to the execution order of insert statement, there are two values ​​of AFTER and BEFORE.

resultType: Specify the result type of select last_insert_id().

(2) Re-test the insert operation.

    @Test
    public void testInsert(){
        User user = new User("张飞", "feifei");
        userDao.addUser(user);
        System.out.println(user);
    }

The execution results are as follows:

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113639709