SpringDataJPA

SpringDataJPA is a branch of SpringData in the Spring family bucket. It is the encapsulation and support of SpringData for JPA. Java Persistence API is a set of interfaces defined by JDK for ORM specification, used for object-oriented programming in the data Persistence layer, shielding database low-level operations. Of all the JPA implementation frameworks, Hibernate is naturally the best, so the underlying implementation used by SpringDataJPA by default is the Hibernate framework. And what we normally call JPA is the JPA implemented by Hibernate by default. As a member of the Spring family, SpringDataJPA also supports SpringBoot by default. We can also directly use SpringBoot to build the SpringDataJPA environment.

Create projects and introduce dependencies


      
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hrp</groupId>
    <artifactId>springboot_jpa</artifactId>
    <version>1.0 the SNAPSHOT</version>

    <! --SpringBoot is the parent project -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4. RELEASE</version>
    </parent>

    <dependencies>
        <! --SpringBootweb developer launcher -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <! -- Spring-data-jPA initiator -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <! -- Test function launcher for integration with junit test function -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <! -- Lombox plugin dependency, SpringBoot built-in, do not need to mark the version number -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <! MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code

Application. Yml configuration file

spring:
  datasource:   SpringBoot Hikari is the built-in database connection pool
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/myshop
    username: root
    password: admin
  jpa:
    database: mysql         Select * from database;
    show-sql: true          Whether to display SQL statements
    generate-ddl: false     Whether to initialize the schema at startup. Default is false
    open-in-view: false     Whether # registered OpenEntityManagerInViewInterceptor, binding the JPA EntityManager to the requesting thread, the default value is: true
    hibernate:
      ddl-auto: update      Use to specify the database table generation policy
  jackson:
    default-property-inclusion: ALWAYS
    time-zone: GMT+8
    date-format: yyyy-MM-dd
Copy the code

SpringBoot start class

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) { SpringApplication.run(MyApplication.class); }}Copy the code

Writing entity classes

@Data
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String name;
    private Integer gender;
    private Date birthday;
    private String phone;
    private String picture;
    private String address1;
    private String address2;
    private String address3;
    private Integer power;
}
Copy the code

SpringBoot+MyBatis+ Mapper = SpringBoot+MyBatis+ Mapper = SpringBoot+MyBatis+ Mapper = SpringBoot+MyBatis+ Mapper

Write a data access layer

public interface UserDao extends JpaRepository<User.Long>, JpaSpecificationExecutor<User> {}Copy the code

Again, you only need to inherit a JpaRepository and JpaSpecificationExecutor interfaces, and SpringDataJPA automatically generates the corresponding simple access methods using dynamic proxies. Two generics in JpaRepository:

  • The first is the entity class type
  • The second is the entity class primary key type

Writing the business layer

Business layer interface

public interface UserService {

    /** ** query user data *@param pageNum
     * @param pageSize
     * @return* /
    Page<User> findByPage(Integer pageNum, Integer pageSize);

}
Copy the code

Business layer implementation

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public Page<User> findByPage(Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum,pageSize);
        Page<User> page = userDao.findAll(pageable);
        returnpage; }}Copy the code
  • Pageable, a paging tool in SpringData, is used here.

Write the Web tier

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;
    
    @GetMapping("page/{pageNum}")
    public ResponseEntity<Page<User>> findByPage(
            @PathVariable("pageNum") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize){
        returnResponseEntity.ok(userService.findByPage(pageNum,pageSize)); }}Copy the code

The last

We start the SpringBoot project and access the API **/user/page/{pageNum}** in a browser.

[Note] Pageable Pageable function in SpringData, the index starts from 0, so if it is in formal development, we should maintain the index by ourselves, and the maintenance strategy should be applied according to the actual needs.