spring-boot-starter-data-jpa 解析

Internet to see, record it, the original: https://blog.csdn.net/Lee_Ho_/article/details/81014215

One: Introduction
    to traditional relational databases, Spring Boot using JPA (Java Persistence API) library resources to achieve operation of the database, in simple terms, JPA is to POJO (Plain Ordinary Java Object) provide persistence of standards, the upcoming Java ordinary objects through object-relational mapping (Object Relational mapping, ORM) persistence to the database.

Two: use
2.1: JPA configuration
    to use JPA and MySQL, Spring Boot create a Maven project, following the introduction of dependence among the POM file:

<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
<artifactId>spring-boot-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>spring-boot-jpa</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<finalName>jpa</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>
repackage
</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>


</project>
application.yml配置:

spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
username: root
password: cuoai1995
jpa:
database: mysql
show-sql: true
#Hibernate ddl auto (validate|create|create-drop|update)
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect

2.2: Solid Modeling:
    To demonstrate the use of JPA, to establish appropriate entity relationships, and demonstrate how to implement solid modeling by way of comment:

Relationships between the entities as shown below:

The solid modeling FIG relationship:

Sector categories:

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "department")
public class Department implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
角色类:

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "role")
public class Role implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
用户类(getter and setter...):

import com.fasterxml.jackson.annotation.JsonBackReference;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "user")
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createDate;

@ManyToOne
@JoinColumn(name = "did")
@JsonBackReference
private Department department;

@ManyToMany(cascade = {}, fetch = FetchType.EAGER)
@JoinTable (name = "user_role", joinColumns @JoinColumn = {(name = "user_id")},
inverseJoinColumns @JoinColumn = {(name = "roles_id")})
Private List <Role> Roles;
used here a new table user_role to represent the dependence of the user and role tables-many.

2.3: Spring Boot Configuration JPA test environment:
Creating JPA configuration class: JpaConfiguration, configuration instructions, see the class comment:

org.springframework.boot.autoconfigure.domain.EntityScan Import;
Import org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import the org.springframework.core.Ordered;
Import org.springframework.core .annotation.Order;
Import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
Import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
Import org.springframework.transaction.annotation.EnableTransactionManagement;

the @Order (Ordered.HIGHEST_PRECEDENCE) / load order / custom components, where the most senior
@ configuration // indicates that this is a configuration class
@EnableTransactionManagement (proxyTargetClass = true) // enable JPA things management
@EnableJpaRepositories (basePackages = "com.example.springbootjpa.repository") // start JPA repository and set the interface repository location
@EntityScan (basePackages = "com.example.springbootjpa.pojo") // entity class position
public class {JpaConfiguration

/ **
* @Description: here explain why to declare Bean object PersistenceExceptionTranslationPostProcessor, citing official documents saying Spring:
* (1) scanned by the Component Spring-Scanning
* (2) Exceptions and platformSpecific the catch and rethrow Them AS One Unified's unchecked Exceptions and the Spring of
But IF you're a using Hibernate A Contextual Sessions and not Hibernate Template, How CAN at the Exception
- Search.com the Take Place?
translation is: @Repository have two effects:
(1): used to be scanned containers:
(2 ): capture platform-specific exceptions and throw them back, as an exception of a Spring unchecked. (Management for the transaction, such as catch exceptions rollback)
However, if you are using Hibernate contextual sessions context of the conversation rather than Hibernate template, then the exception into how it happened?
Well, this is the role of this type of configuration.
@Return *
* /
@Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor () {
return new new PersistenceExceptionTranslationPostProcessor ();
}
}
three: creating entity corresponding Jpa Interface
User Interface:

import com.example.springbootjpa.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

User findByName(String name);
}
部门接口:

import com.example.springbootjpa.pojo.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface DepartmentRepository extends JpaRepository<Department, Long> {
}
角色接口:

com.example.springbootjpa.pojo.Role Import;
Import org.springframework.data.jpa.repository.JpaRepository;
Import org.springframework.stereotype.Repository;

@Repository
public interface RoleRepository the extends JpaRepository <Role, Long> {
}
Four: Test
    after doing the above work, the next step will be tested.

import com.example.springbootjpa.pojo.Department;
import com.example.springbootjpa.pojo.Role;
import com.example.springbootjpa.pojo.User;
import com.example.springbootjpa.repository.DepartmentRepository;
import com.example.springbootjpa.repository.RoleRepository;
import com.example.springbootjpa.repository.UserRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MysqlTest {

private static Logger logger = LoggerFactory.getLogger(MysqlTest.class);

@Autowired
private UserRepository userRepository;

@Autowired
private DepartmentRepository departmentRepository;

@Autowired
private RoleRepository roleRepository;

@Before
public void initData(){
userRepository.deleteAll();
roleRepository.deleteAll();
departmentRepository.deleteAll();

Department department = new Department();
department.setName("开发部");
departmentRepository.save(department);
Assert.assertNotNull(department.getId());

Role role = new Role();
role.setName("admin");
roleRepository.save(role);
Assert.assertNotNull(role.getId());

User user = new User();
user.setName("user");
user.setCreateDate(new Date());
user.setDepartment(department);
List<Role> roles = roleRepository.findAll();
Assert.assertNotNull(roles);
user.setRoles(roles);
userRepository.save(user);
Assert.assertNotNull(user.getId());
}

@Test
public void findPage(){
Pageable pageable = PageRequest.of(0, 10, new Sort(Sort.Direction.ASC, "id"));
Page<User> page = userRepository.findAll(pageable);
Assert.assertNotNull(page);
for (User user : page.getContent()){
logger.info("====user==== user name:{}, department name:{}, role name:{}", user.getName(),
user.getDepartment().getName(), user.getRoles().get(0).getName());
}
}

@Test
public void testFindByName(){
String name = "user";
User user = userRepository.findByName(name);
Assert.assertNotNull(user);
logger.info(user.getName());
}
}
结果:

 

Six: summary of
one: Why should inherit JpaRepository?

To UserRepository for example, to look at the whole system of inheritance:

 

Visible, Jpa repository has provided us with a wealth of ways to meet normal operating requirements.

Two: custom method of implementation:

Jpa itself also provides some rules to customize declarations of methods, for example: using keywords findBy in interfaces, readBy, getBy as a prefix, stitching entity class method attribute field name (first letter capitalized), and can choose some of stitching SQL query keywords to be combined into a method, for example, for a user entity, such keywords can be used:

1.And,如:findByIdAndName(Long id, String name);

2.Or,如:findByIdOrName(Long id, String name);

3.Between,如:findByCreateDateBetween(Date start, Date end);

4.LessThan,如:findByCreateDateLessThan(Date start);

5.GreaterThan,如:findByCreateDateGreaterThan(Date start);

6.IsNull,如:findByNameIsNull();

7.IsNotNull, with the equivalent

8.Like,如:findByNameLike(String name);

9.NotLike: with the equivalent

10.OrderBy,如:findByNameOrderByIdAsc(String name);

11.Not,如:findByNameNot(String name);

12.In,如:findByNameIn(Collection<String> nameList);

13.NotIn, and the equivalent.

Join say above these still can not meet your business requirements, you can also write a custom method using @Query comment + HQL statement to achieve the effect you want.
---------------------
Copyright: This article is CSDN blogger's original article, follow the CC 4.0 by-sa copyright agreement, reproduced "human cage." attach the original source link and this statement.
Original link: https: //blog.csdn.net/Lee_Ho_/article/details/81014215

Guess you like

Origin www.cnblogs.com/linwenbin/p/11357368.html