Home > php教程 > PHP开发 > Use mybatis elegantly

Use mybatis elegantly

高洛峰
Release: 2016-11-22 13:34:50
Original
4571 people have browsed it

Mybatis is quite troublesome to use in the initial stage. It requires various configuration files, entity classes, dao layer mapping associations, and a lot of other configurations. Of course, mybatis has also discovered this shortcoming. In the early stage, it developed a generator that can automatically produce entity classes, configuration files and DAO layer codes based on table results, which can reduce part of the development workload. In the later period, a lot of optimization was also carried out to use annotations and automatically manage DAOs. Layers and configuration files, etc., have developed to the top and this is the model I will talk about today. Mybatis-spring-boot-starter is springboot+mybatis, which can be fully annotated without a configuration file, and can also be easily configured and easily used.

Now think about spring boot, it is awesome. Anything related to spring boot will simplify the complexity.

mybatis-spring-boot-starter

Official description: MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
In fact, myBatis saw that spring boot was so popular and developed a solution to join in the fun, but this It really solves a lot of problems and makes it much smoother to use. mybatis-spring-boot-starter mainly has two solutions, one is to use annotations to solve all problems, and the other is the simplified old tradition.

Of course, any mode needs to first introduce the pom file of mybatis-spring-boot-starter. The latest version now is 1.1.1

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version></dependency>
Copy after login

Okay, let’s introduce the two development modes separately

No configuration file annotation version

That’s everything Use annotations to get it done.

1 Add related 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-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>
     <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 after login

The complete pom package will not be posted here. You can look at the source code directly

2. Application.properties Add related configurations

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-8spring.datasource.username = root
spring.datasource.password = root
Copy after login

springboot will automatically load spring.datasource.* related configurations and data The source will be automatically injected into sqlSessionFactory, and sqlSessionFactory will be automatically injected into Mapper. By the way, you don’t have to worry about anything, just pick it up and use it.

Add @MapperScan

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

to the startup class to scan the mapper package or directly add the annotation @Mapper to the Mapper class. It is recommended to use the above one, otherwise it will be quite troublesome to add annotations to each mapper

3. Develop Mapper

The third step is the most critical one. SQL production is 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);

}
Copy after login

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

// 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 = &#39;someName&#39;;
@Select("Select * from teacher where name = &#39;${name}&#39;)
Teacher selectTeachForGivenName(@Param("name") String name);
Copy after login

4. Using the above three steps, the development of the relevant dao layer is basically completed. When used, it can be injected as a normal class

@RunWith(SpringRunner.class)@SpringBootTestpublic 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 after login

Minimalist XML version

Minimalist XML version maintains the old tradition of mapping files. The optimization is mainly reflected in the implementation layer that does not need to implement dao. The system will automatically The method name finds the corresponding sql in the mapping file.

1、配置

pom文件和上个版本一样,只是application.properties新增以下配置

mybatis.config-locations=classpath:mybatis/mybatis-config.xm

mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
Copy after login

指定了mybatis基础配置文件和实体类映射文件的地址

mybatis-config.xml 配置

<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 after login

这里也可以添加一些mybatis基础的配置

2、添加User的映射文件

<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>
Copy after login

其实就是把上个版本中mapper的sql搬到了这里的xml中了

3、编写Dao层的代码

public interface UserMapper {

    List<UserEntity> getAll();

    UserEntity getOne(Long id);

    void insert(UserEntity user);

    void update(UserEntity user);

    void delete(Long id);

}
Copy after login

对比上一步这里全部只剩了接口方法

如何选择

两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务模式,一个微服务就会对应一个自已的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。

老传统模式比适合大型项目,可以灵活的动态生成SQL,方便调整SQL,也有痛痛快快,洋洋洒洒的写SQL的感觉。


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template