[1] Getting started with Mybatis, adding, deleting, modifying and checking

Mybatis

Need foundation:

  • JDBC
  • Mysql
  • Java basics
  • Maven
  • Junit

1 Introduction

1.1 What is Mybatis

  • MyBatis is an excellent persistence layer framework , which supports custom SQL, stored procedures and advanced mapping.
  • MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets.
  • MyBatis can configure and map primitive types, interfaces and Java POJOs (Plain Old Java Objects) as records in the database through simple XML or annotations.
  • MyBatis was originally an open source project iBatis of Apache . In 2010, this project was migrated from apache software foundation to [google code](https://baike.baidu.com/item/google code/2346604), and was renamed MyBatis.
  • Migrated to Github in November 2013 .

1.2, how to get Mybatis

  • Github:

1.3, endurance

Data persistence

  • Persistence is the process of transforming program data in a persistent state and a transient state
  • Memory: Lost when power is off
  • Database (jdbc), io file persistence.
  • In life: cold storage, canning, photos

Why do we need persistence?

  • There are some objects that cannot be let go of him.

  • Memory is too expensive

1.4, the persistence layer

Dao layer, Service layer, Controller layer

  • The code block to complete the persistence work
  • The boundaries were very clear

1.5 Why do you need Mybatis

  • Convenience

  • The traditional jdbc code is too complicated. In order to simplify, there is a framework, automation

  • Help the program save the data in the database

  • It does not need mybatis. It's easier to get started.

  • advantage:

    • Simple and easy to learn: itself is small and simple. Without any third-party dependencies, the simplest installation is only two jar files + configuration of several sql mapping files. It is easy to learn and easy to use. Through documentation and source code, you can fully grasp its design ideas and implementation.
    • Flexible: Mybatis does not impose any influence on the existing design of the application or database. sql is written in xml, which is convenient for unified management and optimization. All the requirements for operating the database can be met through the sql statement.
    • Uncoupling SQL and program code: By providing a DAO layer, business logic and data access logic are separated, making the system design clearer, easier to maintain, and easier to unit test. The separation of sql and code improves maintainability.
    • Provides mapping tags, supports mapping between objects and database orm fields.
    • Provide object-relational mapping tags and support the establishment and maintenance of object-relationships.
    • Provide xml tags, support writing dynamic sql.

2. The first Mybatis program

Idea: Build an environment -> import Mybatis -> write code -> test

3、CRUD

1、namespace

The package name in the namespace must be consistent with the package name of the Dao/mapper interface!

2、select

Selection, query statement:

  • id: the method name of the corresponding namespace
  • resultType: the return value of sql statement execution
  • parameterType: the input parameter type of the abstract method

Implementation process: the following steps are the same for inserting, modifying, and deleting

  1. Write interface abstract methods
List<User> getUserInfo();
  1. Write the corresponding sql statement in mapper.xml
<mapper namespace="com.kuber.dao.UserMapper">
    <select id="getUserInfo" resultType="com.kuber.pojo.User">
        select * from users
    </select>
</mapper>
  1. test
@Test
    public void getUserInfo(){
    
    
        /*获取SqlSession*/
        SqlSession sqlSession;
        try {
    
    
            /*获取SqlSession*/
            sqlSession = MybatisUtils.getSqlSession();

            /*执行sql*/
            /*相当于 UserMapper mapper = new UserMapperImpl();*/
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.getUserInfo();
            for (User user : users) {
    
    
                System.out.println(user);
            }
            sqlSession.close();
        }finally {
    
    
            MybatisUtils.closeSqlSession();
        }
    }

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-rfdhL4xD-1604566530913)(img\execution result1.

3、insert

  1. Writing interface methods
int addUser(User user);
  1. Write the corresponding sql statement in mapper.xml
	<insert id="addUser" parameterType="com.kuber.pojo.User">
        insert into users values(#{uid},#{username},#{password})
    </insert>
  1. test
@Test
    public void addUser(){
    
    
        /*增删改必须要提交事务*/
        SqlSession sqlSession;
        try {
    
    
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = new User(null,"tonyma","111");
            int num = mapper.addUser(user);
            if(num > 0){
    
    
                System.out.println("插入成功");
            }else {
    
    
                System.out.println("插入失败");
            }
            /*提交事务*/
            sqlSession.commit();
        }finally {
    
    
            MybatisUtils.closeSqlSession();
        }

    }

4、update

  1. Writing interface methods
    int updateUser(User user);
  1. Write the corresponding sql statement in mapper.xml
<update id="updateUser" parameterType="com.kuber.pojo.User">
	update users set username = #{username},password = #{password} where uid = #{uid}
</update>
  1. test
    @Test
    public void updateUser(){
    
    
        SqlSession sqlSession;
        try {
    
    
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int num = mapper.updateUser(new User(7,"jackma","123456"));
            if (num > 0){
    
    
                System.out.println("修改成功");
            }else {
    
    
                System.out.println("修改失败");
            }
            sqlSession.commit();
        }finally {
    
    
            MybatisUtils.closeSqlSession();
        }


    }

5、delete

  1. Writing interface methods
    int deleteUser(int id);
  1. Write the corresponding sql statement in mapper.xml
    <delete id="deleteUser" parameterType="int">
        delete from users where uid = #{id}
    </delete>
  1. test
    @Test
    public void deleteUser(){
    
    
        SqlSession sqlSession;
        try {
    
    
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            int num = mapper.deleteUser(9);
            if (num > 0){
    
    
                System.out.println("删除成功");
            }else{
    
    
                System.out.println("删除失败");
            }
            sqlSession.commit();
        }finally {
    
    
            MybatisUtils.closeSqlSession();
        }


    }
  • Additions, deletions and modifications need to commit the transaction!

6. Error-prone points

  • Do not match the wrong tags

  • resource binding mapper, need to use path

  • Program configuration files must comply with specifications

  • maven resources are not exported

    Add the following code block in the pom.xml file

        <!--在build中配置resours,来防止我们资源导出失败的问题-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        </build>
    

7. Universal Map

Assuming that our entity classes, or tables, fields or parameters in the database are too many, we can use Map

    <insert id="addUser2" parameterType="map">
        insert into users(uid,username,password) values(#{uid},#{uname},#{upwd})
    </insert>
@Test
public void addUser2(){
    
    
    SqlSession sqlSession;
    try {
    
    
        sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uid",8);
        map.put("uname","jacktony");
        map.put("upwd","22333");
        int counter = mapper.addUser2(map);
        if (counter > 0){
    
    
            System.out.println("插入成功!");
        }else {
    
    
            System.out.println("插入失败!");
        }
        sqlSession.commit();
    }finally {
    
    
        MybatisUtils.closeSqlSession();
    }
}

8. Thinking

How to write fuzzy query?

  1. When Java code is executed, pass the wildcard %%
  2. Use wildcards in SQL splicing (note to prevent SQL injection)
    <select id="getLikeUserInfo" parameterType="string" resultType="com.kuber.pojo.User">
        select  * from users where username like #{value}
    </select>
    @Test
    public void getLikeUserInfo(){
    
    
        SqlSession sqlSession;
        try {
    
    
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> users = mapper.getLikeUserInfo("%han%");
            for (User user : users) {
    
    
                System.out.println(user);
            }
        }finally {
    
    
            MybatisUtils.closeSqlSession();
        }

    }

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/109515732