Project started spring boot (c) of the spring boot mybatis be integrated CRUD

Use mybatis CRUD framework basically two basic ways, an extended manner. Are two basic ways to use xml mapping file and use notes. Extension is to use mybatis-plus manner, its usage is similar to spring-data-jpa.

1. dependence introduction

<!--springboot的web起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<-! Mybatis started dependence ->
<dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>2.1.0</version>
</dependency>    
<!-- MySql连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

2.entity entity class

@TableName (value = "tb_user") // needs to be added when using mybatis-plus, establish a relationship with a database table
public class SysUser implements Serializable {

    @TableId (type = IdType.AUTO) // need to be added when using mybatis-plus, primary key generation strategy
    private Long id;

    private String username;


    private String password;

    private String salt;
    private String avatar;
    private String introduce;
    private String remark;
    // omitted get, set method
}

3. Create a profile application.properties

#DB Configuration database information: 
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc: MySQL: /// the Test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource = com.zaxxer.hikari.HikariDataSource .Type

#spring Mybatis integrated environment
#pojo alias scan package
mybatis.type-aliases = cn.zhq.system.entity-package
# mapping file to load Mybatis
mybatis.mapper-locations = classpath: mapper / Mapper.xml *

# print sql
# sql printed to the console
logging.level.cn.zhq.system.mapper = debug
mybatis.type-aliases-package is the location of the entity where the packet, mybatis.mapper-locations is the location of the configuration file. When the initial use of the sql plus the best print configuration, if something goes wrong, then so easy to find out the cause of the error.

4. Create UserMapper class

@Mapper
public interface UserMapper {

}

5. In the application spring boot annotate

@EntityScan ( "cn.zhq.system.entity") // Fill entity class where the location of the package.

After adding this comment, springboot will be able to scan the entity classes.

6. CRUD

6.1 mapper.xml be CRUD

Write a method UserMapper class 6.1.1

    /**
     According to user data queries Name *
     *
     * @param username
     * @return
     */
    SysUser findByName(String username);

6.1.2 Creating UserMapper.xml profile in the mapper directory of resources

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.zhq.system.mapper.UserMapper">
    <select id="findByName" resultType="sysuser" parameterType="String">
      select * from tb_user where username = #{username}
    </select>
</mapper>

Execute a query using the select tag, label use update to add, delete, change operation. Where id is the name of the class method UserMapper, resultType type of the return value, parameterType parameter type is received.

6.2 Use annotations were CRUD

    /**
     * Updated user name
     * @param username
     */
    @Update("update tb_user set username= #{username} where id = #{id}")
    void updateByAvatar(String username,Long id);

After using @Update comment, you no longer need to write UserMapper configuration files, empathy can @Updae additions and deletions to the operation. Also use @Select query. When the query-to-many, many relationships can also be used @Results annotation to specify the type of data to return results, we will not elaborate here.

Above two methods have advantages and disadvantages, using a configuration file written statements advantage of sql low coupling but too much trouble, use annotations manner with respect to the configuration file is relatively simple, but the coupling is high. If it is a simple statement, suggestion is to use annotations, if the statement is complex, using configuration files. Which way the specific use, as the case may be.

6.3 mybatis-plus for CRUD

mybatis-plus similar to the spring data jpa, built-in query, update, delete, insert statements, so that we do not need to write those simple sql statement.

6.3.1 introduced dependence

 <!-- Mybatis Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

6.3.2 application.yml profile

# mybatis-plus
mybatis-plus:
  type-aliases-package: cn.zhq.system.entity
  mapper-locations: classpath:mapper/*.xml
  configuration:
    jdbc-type-for-null: null
  global-config:
    banner: false
type-aliases-package to fill the position where the Entity entity class package. mapper-locations: fill in the map location of the files, if you do not write it in your resources file of mapper configuration error.

6.3.3 related service, serviceImpl, mapper class

service:

public interface UserService  extends IService<SysUser> {


    /**
     * Updates
     *
     * @param sysUser
     */
    void update(SysUser sysUser);
}

serviceImpl:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void update(SysUser sysUser) {
        userMapper.updateById(sysUser);
    }
}

mapper:

@Mapper
public interface UserMapper extends BaseMapper<SysUser> {
}

Although we do not define any methods in UserMapper, but it mybatisPlus integrates a number of ways available to us.

After the execution, sql statement results printed are as follows

Guess you like

Origin www.cnblogs.com/Code-Handling/p/12047735.html