Overview of Spring Data JPA
Overview of ORM
Object Relational Mapping (ORM, or O/RM, or O/R mapping) is a program technology used to realize the conversion between data of different types of systems in object-oriented programming language. In effect, it actually creates a "virtual object database" that can be used in the programming language.
To sum up: the operation entity class in ORM technology is equivalent to operating the database table to establish two mapping relationships:
- Mapping relationship between entity class and table
- Mapping relationship between attributes in entity class and fields in table
Overview of Hibernate
Hibernate is an open source object relational mapping framework. It encapsulates JDBC with very lightweight objects. It establishes the mapping relationship between POJO and database tables. It is a fully automatic orm framework. Hibernate can automatically generate and execute SQL statements, so that Java programmers can use object programming thinking to manipulate the database at will. Hibernate can be used in any situation where JDBC is used, not only in Java client programs, but also in Servlet/JSP Web applications. The most revolutionary thing is that hibernate can replace CMP in JaveEE architecture of EJB application and complete the task of data persistence.
Overview of JPA
The full name of JPA is Java Persistence API, that is, Java Persistence API. It is a set of ORM based specifications launched by SUN company. It is internally composed of a series of interfaces and abstract classes. JPA describes the mapping relationship between object and relational table through JDK 5.0 annotation or XML, and persists the entity object at run time to the database.
Overview of Spring Data Jpa
Spirng Data Jpa is a framework provided by spring to simplify JPA development. By writing dao layer interface according to the agreed method naming rules, you can access and operate the database without writing interface implementation. In addition to the functions of CRUD, it also provides many functions such as paging, sorting, complex query and so on.
Spring Data JPA can be understood as the re encapsulation abstraction of JPA specification, and the underlying layer is implemented by using Hibernate JPA technology.
Spring boot integrates Spring Data JPA
Configuration properties file
## Data source configuration spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=admin spring.datasource.driver-class-name=com.mysql.jdbc.Driver ##Spring Data JPA configuration spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect ##The runtime outputs the sql statements executed by jpa spring.jpa.show-sql=true ## Spring boot starter data JPA automatic mapping creation table action configuration: there are table updates and no table creation spring.jpa.hibernate.ddl-auto=update #Application port server.port=8080 #Application project name #server.context-path=/mydemo #Modify the URIEncoding of tomcat to UTF-8 server.tomcat.uri-encoding=UTF-8 #Focus on solving various coding problems #banner.charset=UTF-8 spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true spring.messages.encoding=UTF-8 #jackson sets the date and time format: time format spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #jackson sets the date and time format: time zone setting spring.jackson.time-zone=GMT+8
Create entity
//Student entity class /** * The database does not have a data table @ Entity to create an Entity * @table(name="studenttb")Automatically create a data table named studenttb in springboot jpahelloworld dB */ @Entity @Table(name="studentdb") public class Student { @Id//Primary key of entity class @GeneratedValue(strategy = GenerationType.IDENTITY)//Auto growth column private Integer id;//id private String name;//full name private String age;//Age }
Spring Data JPA technology also adopts the idea of ORM. Operating entity classes is equivalent to operating database tables. We need to establish two mapping relationships:
- The mapping relationship between Entity class and Table is realized by annotation @ Entity, @ Table;
- The mapping relationship between attributes in the entity class and fields in the table is realized by annotation @ Id, @ GeneratedValue, @ Column.
Annotation labels commonly used in JPA:
- @Entity: marked on the class name as the identification of the entity class;
- @The common option of Table annotation is name, which is used to indicate the Table name of the database.
- @Id: set the object indicator, and the attribute mapping of the identified entity class corresponds to the primary key in the table;
- @GeneratedValue: sets the generation policy of identifier, which is often used with @ Id. Parameter: strategy specifies the specific generation strategy:
Method 1: @ GeneratedValue(strategy=GenerationType.AUTO) is also the default policy, that is, it can be written as @ GeneratedValue; Similar to hibernate's native strategy, the generation method depends on the underlying database.
Mode 2:
@For MySQL, specify "generate type (identity)" = automatic growth policy;
Mode 3:
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqtblpherson") specifies the "sequence" policy, which is commonly used in Oracle, where generator represents the name of the generator. Also, specify @ SequenceGenerator(name = "seqtblpherson", sequenceName = "seqtblpherson", allocationSize = 1) for annotation. Where name specifies the name of the generator (the same as the value of generator), sequenceName specifies the name of the sequence defined in the database, and allocationSize specifies that the sequence grows by 1 each time.
- @Column: describes the definition of this field in the database table and has the following properties.
Name: indicates the name of the field in the database table. By default, the attribute name is the same.
nullable: indicates whether the field is allowed to be null. The default is true.
Unique: indicates whether the field is a unique identifier. The default value is false.
length: indicates the size of the field. It is only valid for fields of String type.
insertable: indicates whether this field should appear in the insert RT statement when the ORM framework performs the insert operation. The default is true.
updateable: indicates whether this field should appear in the UPDATE statement when the ORM framework performs the UPDATE operation. The default is true. This property is useful for fields that cannot be changed once created, such as the birthday field. - columnDefinition: indicates the actual type of the field in the database. Usually, the ORM framework can automatically determine the type of field in the database according to the attribute type, but for the DATE type, it is still unable to determine whether the field type in the database is DATE, TIME or TIMESTAMP. In addition, the default mapping type of String is VARCHAR, which is very useful if you want to map the String type to the BLOB or TEXT field type of a specific database.
- @OrderBy: the order can be specified when loading data.
- @Transient: indicates that this attribute is not a mapping to the field of the database table. The ORM framework will ignore this attribute.
If an attribute is not a field mapping of the database table. Be sure to mark it as @ Transient. Otherwise. The default annotation of ORM framework is @ Basic
Write dao interface
//Interface StudentRepository and inherit the JpaRepository interface public interface StudentRepository extends JpaRepository<Student, Integer>{ //Jparepository < entity class, primary key type of entity class > }
The operation process and principle of Spring Data JPA are as follows:
- A dynamic proxy object is created through the invoke method of JdkDynamicAopProxy;
- JPA operations are encapsulated in the dynamic proxy object SimpleJpaRepository (complete the CRUD of the database with the help of JPA api);
- Complete the database operation through Hibernate.
Write addition, deletion, modification and query of controller layer
@RestController public class StudentController { @Autowired private StudentRepository repository; /** * Query all student records http://localhost:8080/selectAllStu * * @param student * @return */ @GetMapping("/selectAllStu") public Object selectAllStudent() { return repository.findAll(); } /** * Add a student record http://localhost:8080/addStu?name= Liu Yi & age = 100 * * @param student * @return */ @GetMapping("/addStu") public Object addStudent(Student student) { System.out.println("student=>" + student); student = repository.save(student); return student; } /** * Edit a student record http://localhost:8080/updateStu?name= Liu Yi & age = 10 & id = 4 * * @param student * @return */ @GetMapping("/updateStu") public Object updateStudent(Student student) { System.out.println("student=>" + student); student = repository.save(student); return student; } /** * Delete a student record http://localhost:8080/delStu?id=4 * * @param student * @return * @return */ @RequestMapping("/delStu") public Object delStudent(Student student) { System.out.println("student=>" + student); repository.delete(student); return "success"; }
Write main class
@EnableJpaRepositories("com.ctt.springboot.repository") @SpringBootApplication public class SpringDataJpa1Application { public static void main(String[] args) { SpringApplication.run(SpringDataJpa1Application.class, args); } }
Spring JPA persistence layer operation
Default inheritance method
Keyword abstraction method
The naming convention is as follows:
- Condition properties are connected by condition keywords.
- The first letter of a condition property must be capitalized.
Principles for Spring Data JPA to resolve method names
- And - equivalent to the and keyword in SQL. For example, findbyusernameandpassword (string user, string PWD) searches by user name and password.
- Or - equivalent to the or keyword in SQL. For example, findByUsernameOrAddress(String user, String addr) searches by user name or address;
- Between - equivalent to the between keyword in SQL, such as findBySalaryBetween(int max, int min) to query salary in
Between min and max; - LessThan - equivalent to "<" in SQL, such as findBySalaryLessThan(int max);
- GreaterThan - equivalent to ">" in SQL, such as findBySalaryGreaterThan(int min);
- IsNull - equivalent to "is null" in SQL, such as findByUsernameIsNull();
- IsNotNull - equivalent to "is not null" in SQL, such as findByUsernameIsNotNull();
- NotNull - equivalent to IsNotNull;
- Like - equivalent to "like" in SQL, such as findByUsernameLike(String user);
- NotLike - equivalent to "not like" in SQL, such as findByUsernameNotLike(String user);
- OrderBy - equivalent to "order by" in SQL, such as findByUsernameOrderBySalaryAsc(String user);
- Not - equivalent to "! =" in SQL, such as findByUsernameNot(String user);
- In - equivalent to "in" in SQL, such as findByUsernameIn(Collection userList). The parameters of the method can be Collection type, array or variable length parameters;
- NotIn - equivalent to "not in" in SQL, such as findByUsernameNotIn(Collection userList). The parameter of the method can be Collection type, array or variable length parameter;
Use of Spring Data JPA keyword abstraction method
- On COM ysd. springboot. Add the following code to the StudentRepository class under repository configuration:
public interface StudentRepository extends JpaRepository<Student, Integer>{ //Fuzzy search for student information by name public List<Student> findByStudentNameContaining(String name); }
- Add the following code under the StudentController class:
/*** * http://localhost:8080/findStudentByName?name=Liu * @param name * @return */ @RequestMapping("/findStudentByName") public Object findStudentByName(String name) { List<Student> student = repository.findByStudentNameContaining(name); return student; }