SpringBoot integrates JDBC, Mybatis, springdata and JPA

Posted by Random on Sat, 19 Feb 2022 01:02:35 +0100

1. Spring boot integrates JDBC

(1) In POM Import related dependencies in XML

 <!--Inherit parent package-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
    </parent>
 <dependencies>
        <!--jdbc rely on-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
    </dependencies>

(2) Add database related information to the configuration file

application.yml

server:
 port: 8080
spring:
 thymeleaf:
	 prefix: classpath:/templates/
	 suffix: .html
	 mode: HTML5
	 encoding: UTF-8
 datasource:
	 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
	 username: root
	 password: 
	 driver-class-name: com.mysql.cj.jdbc.Driver

(3) Create entity classes and interfaces, and use JdbcTemplate in Repository or Service layer implementation classes

SpringBoot encapsulates JDBC. It does not need to adopt the native method, but only needs to use JdbcTemplate

Principle: when SpringBoot starts, it will find the data source to be connected according to the configuration file yml, and automatically create an object named JdbcTemplate to register into the bean

The bottom layer of the JdbcTemplate is to connect the data source through jdbc. Because it is encapsulated, curd can be realized by directly calling the interface method

new BeanPropertyRowMapper(Class) can map the result set to an entity class

Implementation class

@Repository
public class UserRepositoryImpl implements UserRepository {
 @Autowired
 private JdbcTemplate jdbcTemplate;
 @Override
 public List<User> findAll() {
    //Query uses the query() method to map the result set into an entity class through the new BeanPropertyRowMapper
 	return jdbcTemplate.query("select * from user",new BeanPropertyRowMapper<>(User.class));
 }
 @Override
 public User findById(long id) {
 	return jdbcTemplate.queryForObject("select * from user where id = ?",newObject[]{id},new BeanPropertyRowMapper<>(User.class));
 }
 @Override
 public void save(User user) {
 	jdbcTemplate.update("insert into user(name,score) values(?,?)",user.getName(),user.getScore());
 }
 @Override
 public void update(User user) {
 	jdbcTemplate.update("update user set name = ?,score = ? where id = ?",user.getName(),user.getScore(),user.getId());
 }
 @Override
 public void deleteById(long id) {
 	jdbcTemplate.update("delete from user where id = ?",id);
 }
}


2. Spring boot integrates Mybatis

(1) pom. Import dependency in XML

 <!--Inherit parent package-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
    </parent>
    <dependencies>
<!--        &lt;!&ndash;jdbc rely on&ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-jdbc</artifactId>-->
<!--            <version>2.4.1</version>-->
<!--        </dependency>-->

<!--        MyBatis Related dependency-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
    </dependencies>

(2) Create an entity class, Repository or Service interface, and then create the mapper corresponding to the interface xml

Important: mapper XML is created in the Resources folder

(if the XML is gray, try to change the version of mybatis configuration in pom.xml)

mapper.xml is an sql statement used to implement interface business methods

mapper namespace: business interface path
id: method name, resultType: return type, parameterType: parameter type

<?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.ruoxi.mapper.UserRepository">
    <select id="findAll" resultType="User">
        select * from user limit #{param1},#{param2}
    </select>
    <select id="count" resultType="int">
        select count(id) from user
    </select>
    <select id="findById" parameterType="long" resultType="User">
        select * from user where id = #{id}
    </select>
    <insert id="save" parameterType="User">
        insert into user(name,score) values(#{name},#{score})
    </insert>
    <update id="update" parameterType="User">
        update user set name = #{name},score = #{score} where id = #{id}
    </update>
    <delete id="deleteById" parameterType="long">
        delete from user where id = #{id}
    </delete>
</mapper>

(3) Write application YML configuration file, add the configuration of mybatis (including data source, etc.)

mapper-locations: classpath:/mapper/*.xml means that mapper scans all xml files under Resources / mapper

Type aliases package: represents to extract the path of the entity class

server:
 port: 8080
spring:
 thymeleaf:
	 prefix: classpath:/templates/
	 suffix: .html
	 mode: HTML5
	 encoding: UTF-8
 datasource:
	 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
	 username: root
	 password: 
	 driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
 mapper-locations: classpath:/mapper/*.xml
 type-aliases-package: com.ruoxi.entity

(4) Add @ MapperScan annotation to the Application startup class

@SpringBootApplication
@MapperScan("com.ruoxi.repository")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

explain:

At this step, the automatic scanning of the Application startup class cannot scan the business layer interface, because the business layer interface is managed by mybatis

At this time, the @ MapperScan annotation should be added to the Application startup class (and the mapper should also be scanned into the IOC), so that the business layer interface can be managed by Spring, so that the @ Autowire annotation in the business implementation class can take effect

3. SpringBoot integrates SpringData JPA

Introduction to SpringDataJPA:

JPA: describe the mapping relationship between object and relational table by annotation or XML, and persist the entity object in the database at run time

jpa hibernate framework implements JPA, and the bottom layer of spring data JPA is realized through jpa hibernate (jpa hibernate is a fully automated mapping framework)

Spring data: Spring data provides a framework for manipulating data

SpringData JPA: SpringData JPA is a module based on JPA standard operation data under the SpringData framework. It operates based on JPA standard data and simplifies the code of operation persistence layer. It only needs to write business interface and inherit JpaRepository interface

That is, the method that implements curd does not need to implement the interface or handwritten sql

Spring data JPA usage steps

(1) pom. Import dependency in XML

<!-- Import jpa Dependence of -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
   <version>2.4.1</version>
</dependency>

(2) Create an entity class and use some annotations to realize the mapping (realize the mapping of entity class and table)

@Entity: represents the entity class mapped to the table

@id: indicates the primary key

@GeneratedValue(strategy = GenerationType.AUTO): indicates that the generation strategy is self increment

@Column: represents the mapping of attributes other than the primary key

@Data
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    @Column
    String name;
}

(3) Write the business interface and inherit the generic interface JpaRepository

Jparepository < T, ID > generic parameter description: t is entity class and ID is primary key type (basic data type cannot be used)

public interface UserRepository extends JpaRepository<User,Long> {
    //You can define some methods other than curd implemented by jpa
    public User getById(); 
}

Supplement 1: customize some methods with naming conventions. jpa will automatically implement this method, such as getById() above

Supplement 2: method of JpaRepository interface

@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
    List<T> findAll();

    List<T> findAll(Sort var1);

    List<T> findAllById(Iterable<ID> var1);

    <S extends T> List<S> saveAll(Iterable<S> var1);

    void flush();

    <S extends T> S saveAndFlush(S var1);

    void deleteInBatch(Iterable<T> var1);

    void deleteAllInBatch();

    T getOne(ID var1);

    <S extends T> List<S> findAll(Example<S> var1);

    <S extends T> List<S> findAll(Example<S> var1, Sort var2);
}

(4) Create Handler and inject business interface (here is UserRepository)

Note: findById(id) returns an Optional class in the source code. You need to call the get() method to get the entity class object. You can also add the getById method instead

@RestController
public class UserHandler {
    @Autowired
    private UserRepository userRepository;

    //Here, you can directly call the method of the business interface, that is, the method implemented by JpaRepository
    @GetMapping("/findAll")
    public List<User> findAll(){
        return userRepository.findAll();
    }

    @GetMapping("/findById")
    public User findById(Long id){
        userRepository.getById();
        return userRepository.findById(id).get();
    }

    //RequestBody is used to convert json objects from the client into java objects
    @PostMapping("/save")
    public User save(@RequestBody User user){
       return userRepository.save(user); //Add without id primary key
    }

    //RequestBody is used to convert json objects from the client into java objects
    @PutMapping("/put")
    public User update(@RequestBody User user){
        return userRepository.save(user); //If there is an id primary key, the update will be overwritten
    }

    @DeleteMapping("/delete/{userId}")
    public void delete(@PathVariable("userId") Long id){
        userRepository.deleteById(id);
    }
}

Topics: Java