A new project has been launched these days because the project team members have been using MyBatis. Although I prefer the minimalist mode of JPA, I still choose MyBatis in order to maintain the uniformity of the project. I went to the Internet to find relevant materials about the combination of Spring Boot and Mybatis, and it was tiring to see all kinds of forms. I finally found the two simplest modes by combining the official demo and documents of Mybatis, and spent a day summarizing and sharing them.

The essence of ORM framework is to simplify the coding of database operation in programming. Until now, there are basically two, one is Hibernate, which claims to be able to write a SENTENCE of SQL, and one is Mybatis, which can flexibly debug dynamic SQL. Both have their own characteristics and can be flexibly used according to the needs in enterprise-level system development. Found an interesting phenomenon: traditional enterprises mostly like to use Hibernate, Internet industry usually use Mybatis.

Hibernate features are all SQL generated in Java code, do not jump out of the program to write (see) SQL, with programming integrity, development to the top is spring Data JPA mode, basically according to the method name can generate the corresponding SQL. Springboot (5) : The use of Spring Data JPA.

Mybatis is a bit of a hassle to use initially, requiring various configuration files, entity classes, DAO layer mapping associations, and a lot of other configurations. Of course, Mybatis also found this disadvantage. At the beginning, it developed a generator which can automatically produce entity class, configuration file and DAO layer code according to the table results, which can reduce part of the development amount. Later also carried out a lot of optimization can use annotations, automatic management dao layer and configuration files, etc., to the top of the development is today to talk about this mode, mybatis-spring-boot-starter is springboot+ Mybatis can completely annotate without configuration files, It can also be configured easily and easily.

Now think of Spring Boot is awesome, as long as anything associated with Spring Boot is simplified.

mybatis-spring-boot-starter

Official note: MyBatis spring-boot-starter will help you use MyBatis with Spring Boot Boot has developed a solution to the problem, but it solves a lot of problems and makes it a lot easier to use. Mybatis – Spring-boot-Starter has two main solutions, one is to use annotations to solve everything, and the other is a simplified old tradition.

Mybatis -spring-boot-starter is a poM file that needs to be imported into any mode. The latest version is 1.1.1.

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> The < version > 1.1.1 < / version > < / dependency >Copy the code

Ok, the two development modes are introduced separately

The no profile annotation version is all done using annotations.

1 Add maven files

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>  <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.1.1 < / version > < / dependency > < the dependency > <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>Copy the code

Complete POM package here is not posted, we directly look at the source code

2. Application. Properties Add the configuration

mybatis.type-aliases-package=com.neo.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test1? useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = rootCopy the code

Springboot automatically loads the spring.datasource.* configuration, the datasource is automatically injected into the sqlSessionFactory, and the sqlSessionFactory is automatically injected into the Mapper. Just pick it up and use it.

Add mapper package scan @mapperscan to the startup class

@SpringBootApplication @MapperScan("com.neo.mapper ") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

You can also add annotations to the Mapper class by adding @mapper annotations to the Mapper class

3, Mapper development step 3 is the most critical piece, SQL production is here

public interface UserMapper {    
    @Select("SELECT * FROM users ")     
    @Results({        
       @Result(property = "userSex ",  column = "user_sex ", javaType = UserSexEnum.class),        
       @Result(property = "nickName ", column = "nick_name ")
    })   
    List<UserEntity> getAll();
    
    @Select("SELECT * FROM users WHERE id=# {id} ")
    @Results({        
        @Result(property = "userSex ",  column = "user_sex ", javaType = UserSexEnum.class),
        @Result(property = "nickName ", column = "nick_name ")
    })    
    UserEntity getOne(Long id);    
    
    @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex}) ")    
    void insert(UserEntity user);    
    
    @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id=#{id} ")
    void update(UserEntity user);    
    
    @Delete("DELETE FROM users WHERE id=#{id} ")    
    void delete(Long id);

}Copy the code

In order to be closer to the production, I have underlined the two attributes user_sex and Nick_name in the database, which are inconsistent with the entity class attribute name. In addition, user_sex uses enumeration

@select is the annotation of the query class, which is used by all queries

@result decorates the returned Result set. The associated entity class attribute corresponds to the database field one-to-one. If the entity class attribute and database attribute name are the same, this attribute is not needed to decorate.

@insert for database use, passing directly into the entity class will automatically parse the attribute to the corresponding value

@update takes care of the modification, or you can pass in the object directly

@delete is responsible for deleting

See here for more properties

Note the difference between using the # sign and the $sign:

// This example creates a prepared statement, something like select * from teacher where name = ? ; @Select("Select * from teacher where name=# {name} ") Teacher selectTeachForGivenName(@Param("name ") String name); // This example creates n inlined statement, something like select * from teacher where name = 'someName'; @Select("Select * from teacher where name='${name}' ") Teacher selectTeachForGivenName(@Param("name ") String name);Copy the code

4. Use the above three steps to basically complete the development of the relevant DAO layer, and use it as a common class injection into it

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {    
    @Autowired
    private UserMapper UserMapper;    
    @Test
    public void testInsert() throws Exception {
        UserMapper.insert(new UserEntity("aa ", "a123456 ", UserSexEnum.MAN));
        UserMapper.insert(new UserEntity("bb ", "b123456 ", UserSexEnum.WOMAN));
        UserMapper.insert(new UserEntity("cc ", "b123456 ", UserSexEnum.WOMAN));

        Assert.assertEquals(3, UserMapper.getAll().size());
    }   
   
    @Test
    public void testQuery() throws Exception {
        List<UserEntity> users = UserMapper.getAll();
        System.out.println(users.toString());
    }    
    
    @Test
    public void testUpdate() throws Exception {
        UserEntity user = UserMapper.getOne(3l);
        System.out.println(user.toString());
        user.setNickName("neo ");
        UserMapper.update(user);
        Assert.assertTrue(("neo ".equals(UserMapper.getOne(3l).getNickName())));
    }
}Copy the code

Source controler layer has a complete add, delete, change check, here is not posted

Minimal XML version

The minimalist XML version maintains the old tradition of mapping files. The optimization is mainly reflected in the implementation layer, which does not need to implement the DAO. The system will automatically find the corresponding SQL in the mapping file based on the method name.

1. Configure the POM file as in the previous version, with the following additions to application.properties

mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xmlCopy the code

Specifies the address of the myBatis base profile and entity class mapping file

Mybatis – config. The XML configuration

<configuration>
    <typeAliases>
        <typeAlias alias="Integer " type="java.lang.Integer " />
        <typeAlias alias="Long " type="java.lang.Long " />
        <typeAlias alias="HashMap " type="java.util.HashMap " />
        <typeAlias alias="LinkedHashMap " type="java.util.LinkedHashMap " />
        <typeAlias alias="ArrayList " type="java.util.ArrayList " />
        <typeAlias alias="LinkedList " type="java.util.LinkedList " />
    </typeAliases>
</configuration>Copy the code

Here you can also add some basic configurations for MyBatis

2. Add User mapping files

<mapper namespace="com.neo.mapper.UserMapper " > <resultMap id="BaseResultMap " type="com.neo.entity.UserEntity " > <id column="id " property="id " jdbcType="BIGINT " /> <result column="userName " property="userName " jdbcType="VARCHAR " />  <result column="passWord " property="passWord " jdbcType="VARCHAR " /> <result column="user_sex " property="userSex " javaType="com.neo.enums.UserSexEnum "/> <result column="nick_name " property="nickName " jdbcType="VARCHAR " /> </resultMap> <sql id="Base_Column_List " > id, userName, passWord, user_sex, nick_name </sql> <select id="getAll " resultMap="BaseResultMap " > SELECT <include refid="Base_Column_List " /> FROM users </select> <select id="getOne " parameterType="java.lang.Long " resultMap="BaseResultMap " > SELECT <include refid="Base_Column_List " /> FROM users WHERE id = #{id} </select> <insert id="insert " parameterType="com.neo.entity.UserEntity " > INSERT INTO users (userName,passWord,user_sex) VALUES (#{userName}, #{passWord}, #{userSex}) </insert> <update id="update " parameterType="com.neo.entity.UserEntity " > UPDATE users SET <if test="userName ! =n ull ">userName = #{userName},</if> <if test="passWord ! =n ull ">passWord = #{passWord},</if> nick_name = #{nickName} WHERE id = #{id} </update> <delete id="delete " parameterType="java.lang.Long " > DELETE FROM users WHERE id =#{id} </delete> </mapper>Copy the code

You’re essentially moving the SQL from the previous version of Mapper into the XML here

3. Write code for the Dao layer

public interface UserMapper {
    List<UserEntity> getAll();
    UserEntity getOne(Long id);    
    void insert(UserEntity user);    
    void update(UserEntity user);    
    void delete(Long id);
}Copy the code

Compared to the previous step, this is all just interface methods

4, the use of

Use and the last version is no different, we look at the code

XML configuration version: github.com/ityouknow/s…

How to choose

The two modes have their own characteristics, the annotated version is suitable for simple and fast mode, in fact, like the popular micro-service mode now, a micro-service will correspond to a own database, the demand for multi-table connection query will be greatly reduced, will be more and more suitable for this mode.

The old traditional mode is more suitable for large projects, can be flexible and dynamic SQL generation, convenient to adjust SQL, but also have a quick, grandiose feeling of writing SQL.

Full code address: github.com/ityouknow/s…

Article source: mp.weixin.qq.com/s/1ikYOxF9X…

More reference content: www.roncoo.com/course/list…