Spring Boot (VI): How elegant use Mybatis

Two days launched a new project because the project team members have been using Mybatis, although personally prefer Jpa this minimalist mode, but in order to maintain the unity project technology selection or set the Mybatis. Look to the Internet to find relevant information on Spring Boot and Mybatis combination of various forms are, looking tired people, a combination of official documents Mybatis Demo and finally found the simplest of the two modes, I spent a day after the time out to share summary.

Nature Orm framework is coded to simplify programming operation of the database, developed to basically got left two, and one is declared can not write a Sql Hibernate, one is flexible debugging Mybatis dynamic Sql, both of which have their own characteristics , it can be used flexibly in the enterprise system development based on demand. I found an interesting phenomenon: the most traditional companies prefer to use Hibernate, the Internet industry generally use Mybatis.

Sql Hibernate feature is that all are used to generate the Java code, do not jump out of the program to write (see) Sql, the integrity of the program has developed to the very top is the Spring Data Jpa this model, basically can be generated according to the method name corresponding Sql, and there do not understand can read my previous article Spring Boot (e): using Spring Data Jpa of .

Comparative initial Mybatis cumbersome, requiring various configuration files, the entity class, association Dao layer mapping, there is a big push other configurations. Of course, also we found that Mybatis drawbacks, early in the development of generator can automatically produce the results according to Table entity class, profile codes, and Dao layer, part of the developer amount can be reduced; later also a lot of optimization may be used annotated, automatic management Dao layer, and configuration files, to the development of this model is the top of today's talk, and mybatis-spring-boot-starter is the Spring Boot + Mybatis can not fully comment configuration file, you can simply configure easily get started.

Now that I think Spring Boot is Niubi ah, anything as long associated with Spring Boot is Made Simple.

mybatis-spring-boot-starter

The official explanation: MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
in fact Mybatis look so hot Spring Boot also developed a set of solutions along for the ride, but this does solve a lot of problems Minato, use really a lot smoother. mybatis-spring-boot-starterThere are two solutions, one is to use annotations to solve all problems, one is the old traditional simplified.

Of course, any pattern will begin with the introduction of mybatis-spring-boot-starterPom file, and the current version is 2.0.0

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>

 

Well down two development models are introduced

No configuration file version comment

Use annotations is all done.

1 Add Maven related files

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.0</version>
    </dependency>
     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

 

Pom complete package here is not posted, it looks directly at the source

2, application.properties add the relevant configuration

mybatis.type-aliases-package=com.neo.model

spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

 

Spring Boot will automatically load  spring.datasource.* the relevant configuration data source is automatically injected into the sqlSessionFactory in sqlSessionFactory automatically injected into the Mapper, yes, everything you do not have control, directly take up the use of the line.

Add a scanning start packet mapper class@MapperScan

@SpringBootApplication
@MapperScan("com.neo.mapper")
public class MybatisAnnotationApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisAnnotationApplication.class, args);
    }
}

 

Or add annotations directly in the Mapper class above @Mapper, it is recommended that the use of the above, or to add a comment to each mapper also very troublesome

3, development Mapper

The third step is the most critical piece, Sql production are all 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);

}

 

To get closer to production I've come to user_sex, nick_name two attributes in the database underlined inconsistent entity class and attribute names, using the enumeration another user_sex

  • @Select class is annotated queries, all queries are using this
  • @Result modified result set returned, related entity class properties and database fields correspond, if the entity class attributes and attribute database name remains the same, there is no need to modify this property.
  • @Insert into the database used, directly into the entity class value corresponding to the attribute automatically resolves
  • @Update responsible for modifying or directly incoming object
  • @delete responsible for deleting

Learn more here Property Reference

Note that using the # symbol and $ symbols differently:

// 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);

 

4, using

The above three steps basically completed Mapper layer related to the development, use of time as a regular class will be able to inject into the

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testInsert() throws Exception {
        userMapper.insert(new User("aa1", "a123456", UserSexEnum.MAN));
        userMapper.insert(new User("bb1", "b123456", UserSexEnum.WOMAN));
        userMapper.insert(new User("cc1", "b123456", UserSexEnum.WOMAN));

        Assert.assertEquals(3, userMapper.getAll().size());
    }

    @Test
    public void testQuery() throws Exception {
        List<User> users = userMapper.getAll();
        System.out.println(users.toString());
    }


    @Test
    public void testUpdate() throws Exception {
        User user = userMapper.getOne(30l);
        System.out.println(user.toString());
        user.setNickName("neo");
        userMapper.update(user);
        Assert.assertTrue(("neo".equals(userMapper.getOne(30l).getNickName())));
    }
}

 

Source Controller layer in full CRUD, there is not posted

Minimalist xml version

Xml mapping files kept minimalist version of the old tradition, the interface layer only need to define an empty method, the system will automatically find the corresponding Sql in the mapping file based on the method name.

1, the configuration

pom file and the previous version, just application.propertiesadd the following configuration

mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

 

Specifies an address Mybatis basic configuration file and the entity class mapping file

mybatis-config.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>

 

Here you can also add some basic configuration Mybatis

2, Add User mapping file

<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 != null">userName = #{userName},</if>
        <if test="passWord != null">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>

 

In fact, the previous version of Sql Mapper moved here in the xml

3, coding layer Mapper

public interface UserMapper {

    List<UserEntity> getAll();

    UserEntity getOne(Long id);

    void insert(UserEntity user);

    void update(UserEntity user);

    void delete(Long id);

}

 

Step, where only you need to define the interface method comparison

4, using

And using the previous version without any distinction, we see the sample code corresponding article it

how to choose

Two models have different features, notes version for simple and fast mode, in fact, as they are now such a popular micro-service model, a micro will correspond to a service of their own database, multi-table join query demand will be greatly reduced, it will be more the more fit to this model.

Older than the traditional model for large-scale projects, the flexibility of dynamically generated Sql, Sql easy to adjust, but also very much love, eloquent writing of Sql feeling.

Article content has been upgraded to Spring Boot 2.x

Sample Code -github

Sample code - Code Cloud

 

This article comes from: https://www.cnblogs.com/ityouknow/p/6037431.html

Guess you like

Origin www.cnblogs.com/JonaLin/p/11411008.html