A new project has been launched in the past two days because the members of the project team have always used mybatis. Although I personally prefer the minimalist model of jpa, mybatis is still determined to maintain the unified technology selection in order to maintain the project. I went online to find relevant information about the combination of spring boot and mybatis. There are various forms, which makes people tired of reading it. Combining mybatis' official demo and documents, I finally found the two simplest modes. I spent a day summarizing it and sharing it.
The essence of the orm framework is to simplify the encoding of operating databases in programming. Now there are basically two companies left. One is to claim that you can not write a sentence of SQL hibernate, and the other is to flexibly debug mybatis of dynamic SQL. Both have their own characteristics and can be flexibly used according to needs in enterprise-level system development. I found an interesting phenomenon: most traditional companies like to use hibernate, and the Internet industry usually uses mybatis.
The characteristic of hibernate is that all SQL is generated using Java code, and there is no need to write (read) SQL without jumping out of the program. It has programming integrity. It develops to the top of the model. Basically, the corresponding SQL can be generated based on the method name. If you don’t know much, you can read my previous article on the use of spring data jpa.
Mybatis is very troublesome in the early stage, requiring various configuration files, entity classes, dao layer mapping associations, and a lot of other configurations. Of course, mybatis also discovered this disadvantage. In the early stage, the generator was developed, which can automatically produce entity classes, configuration files and dao layer code based on the table results, which can reduce part of the development volume; in the later stage, a lot of optimizations can be used to use annotations, automatically manage dao layers and configuration files, etc., and the development to the top is the model we are going to talk about today. Mybatis-spring-boot-starter is springboot+mybatis can completely annotate without configuration files, and can also be simple configuration and easy to get started.
Now think about it, spring boot is awesome. As long as you associate anything with spring boot, it will simplify it.
mybatis-spring-boot-starter
Official description: MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
In fact, myBatis has developed a solution to join in the fun because of spring boot so popular, but this one has indeed solved many problems and is indeed much smoother to use. There are two main solutions for mybatis-spring-boot-starter. 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. Now the latest version is 1.1.1 (it just happens to be on Double 11 :))
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency>
I'll introduce two development models
No configuration file annotation version
It is done with annotations.
1 Add relevant maven files
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactIdId</groupId><artifactId >spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><depen dency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-c onnector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency></dependencies>
I won't post the complete pom package here, please read the source code directly
2. Application.properties add relevant configurations
mybatis.type-aliases-package=com.neo.entityspring.datasource.driverClassName = com.mysql.jdbc.Driverspring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8spring.datasource.username = rootspring.datasource.password = root
Springboot will automatically load the relevant configuration of spring.datasource.*, and the data source will be automatically injected into the sqlSessionFactory. The sqlSessionFactory will be automatically injected into the mapper. By the way, you don’t have to worry about everything, just pick it up and use it.
Add a scan of mapper package in the startup class @MapperScan
@SpringBootApplication@MapperScan("com.neo.mapper")public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}Or just add annotation @Mapper on the Mapper class. It is recommended to use the above one, otherwise it will be quite troublesome to add annotation to each mapper.
3. Develop Mapper
The third step is the most critical part, and 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);}In order to be closer to production, I specially underlined the two attributes of user_sex and nick_name in the database and the entity class attribute names are inconsistent. In addition, user_sex uses enumerations
@Select is an annotation of the query class, and all queries use this
@Result Modify the result set returned, and the associated entity class attributes and database fields correspond one by one. If the entity class attributes and database attribute names are consistent, this attribute is not needed to modify.
@Insert Insert the database to use, directly passing the entity class will automatically parse the attribute to the corresponding value
@Update is responsible for modifying, and can also be directly passed into the object
@delete is responsible for deleting
For more properties, please refer to here: http://www.mybatis.org/mybatis-3/zh/java-api.html
Note that the difference between using # symbol and $ 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 = 'someName';@Select("Select * from teacher where name = '${name}'")Teacher selectTeachForGivenName(@Param("name") String name);4. Use
The above three steps basically complete the relevant layer development. When using it, just use it as an ordinary class and it can be injected into it.
@RunWith(SpringRunner.class)@SpringBootTestpublic class UserMapperTest {@Autowiredprivate UserMapper UserMapper;@Testpublic 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());}@Testpublic void testQuery() throws Exception {List<UserEntity> users = UserMapper.getAll();System.out.println(users.toString());}@Testpublic 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())));}}There are complete additions, deletions, modifications and searches in the source code, so I won't post them here
Minimalist xml version
The minimalist XML version maintains the old tradition of mapping files. Optimization is mainly reflected in the implementation layer that does not need to be implemented. The system will automatically find the corresponding SQL in the mapping file according to the method name.
1. Configuration
The pom file is the same as the previous version, except that the following configuration is added to application.properties
mybatis.config-locations=classpath:mybatis/mybatis-config.xmlmybatis.mapper-locations=classpath:mybatis/mapper/*.xml
Specifies the address of the mybatis basic configuration file and 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 mybatis configuration
2. Add the User's 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 usersWHERE 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 FROMusers WHERE id = #{id}</delete></mapper>In fact, it was just moving the mapper sql from the previous version to the xml here
3. Write Dao layer code
public interface UserMapper {List<UserEntity> getAll();UserEntity getOne(Long id);void insert(UserEntity user);void update(UserEntity user);void delete(Long id);}Compared with the previous step, there are only interface methods left.
4. Use
There is no difference between using it and the previous version, please look at the code
How to choose
The two modes have their own characteristics. The annotated version is suitable for simple and fast modes. In fact, like the popular microservice model nowadays, a microservice will correspond to its own database. The demand for multi-table connection query will be greatly reduced, and it will become more and more suitable for this mode.
The old traditional model is more suitable for large projects. It can flexibly generate SQL dynamically, which is convenient for adjusting SQL, and also has the feeling of writing SQL with great pleasure and sleekness.
Sample code - github: https://github.com/ityouknow/spring-boot-examples
Example code - Code Cloud: https://gitee.com/ityouknow/spring-boot-examples