Integration of mybatis and jpa persistence in springboot learning 6

Keywords: Mybatis SQL xml Database

Integrate mybatis

Introduction of jar package

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

Using springboot to create tables for database and execute sql

spring:
	datasource:
		schema:
		- classpath:sql/deparmat.sql
		- classpath:sql/employee.sql

Annotated edition

Without any configuration, it can be developed directly

@Mapper
public interface DepartmentMapper {
    //@Options(useGeneratedKeys = true,keyProperty = "id") uses the auto primary key and encapsulates the primary key into the object
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);
}

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;
    @GetMapping
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
    //Parameter in access path {id} 
    @GetMapping("/dept/{id}")
    public Department selectDept(@PathVariable("id") Integer id){
        return null;
    }
}

If the field in the database is named aaubb, and the attribute is AA BB, how can it directly correspond to it? Use the hump naming method of mybatis, which is set by user.

//@MapperScan(value="com.xxx.mapper") can be configured to all configuration classes
@MapperScan(value="com.xxx.mapper")//Batch scan package, do not add @ mapper on each mapper class or interface
@Configuration
public class CustomConfig {
 @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);//Set hump name
            }
        };
    }
}

xml configuration mode

Write sql to xml file

<!--mybatis Global profile mybatis-config.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- Print query statement -->
        <setting name="logImpl" value="Log4J"/>
         <!-- Open hump nomenclature -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
//Mapping file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.DepartmentMapper">
<insert id="insertEmp">
insert into Table name(Field 1, field 2) values(#{},#{})
</insert>
</mapper>

Then configure it in application.yml

mybatis:
	config-location: classpath:mybatis/mybatis-config.xml      //This is the main profile path
	mapper-location: classpath:mybatis/mapper/*.xml   //Configuration of database mapping file

Integrating SpringData JPA

Jpa(java persistence api): JPA is an ORM specification and a subset of Hibernate functions
jpa:orm(object Relation Mapping)

First, we need to introduce jpa jar package.

<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>2.1.9.RELEASE</version>
		</dependency>

1) / write an entity class (bean) and data table for mapping, and configure the mapping relationship

//Using jpa to configure the mapping relationship
@Entity//Tell jpa that it is an entity class (a class mapped to a data table)
@Table(name = "tb_user")//Used to specify the corresponding table. If omitted, the default is user table.
public class User {
    @Id//This is a primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)//Self increasing primary key
    private Integer id;
    @Column(name = "last_name",length = 50)//This is a column corresponding to the database
    private String lastName;
    @Column//Omitting the default column name is the property name
    private String email;
}

2) write dao interface to operate entity class

//Configuration in yml
spring:
	jpa:
		hibernate:
			ddl-auto: update //Update or create database table structure
		show-sql: true //The console displays sql
//Inherit JpaRepository to complete the operation of database
public interface UserRepository extends JpaRepository<User,Integer>{
}

Posted by intergroove on Fri, 01 Nov 2019 15:58:46 -0700