This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging


preface

In the wrong direction, efforts are wasted

Usually you put in a lot of time, but you don’t get much benefit. Just like sometimes a lot of friends ask me, I am how to learn a content I have never touched. My personal experience strongly suggests that you should not learn too much theoretical content, but try to practice and make some Demo cases of what you want to learn. It’s kind of like when you buy a bike, do you tear it down first and learn how it works, or do you ride it around first? Even if you fall, but that is the experience after you have to go through.

The SpringDataJpa persistence layer operation was discussed earlier, please see the blogger’sThe SpringDataJpa series. Welcome to follow!


Create the entity

In com. Cyj. Springboot. Entity created under Student class, as follows:

package com.cyj.springboot.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.format.annotation.DateTimeFormat; / * * * because database tables @ no Entity created Entity * @ table (name = "studenttb") in springbootjpahelloworlddb automatically create a table called studenttb data table * / @ the Entity @table (name="studenttb") public class Student {@id / @generatedValue // Private Integer studentId; // Student id private String studentName; // Student name private Integer studentAge; @datetimeFormat (pattern=" YYYY-MM-DD HH: MM :ss") private Date studentBirthday; // Student age @datetimeFormat (pattern=" YYYy-MM-DD HH: MM :ss") private Date studentBirthday; Public Integer getStudentId() {return studentId; } public void setStudentId(Integer studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public Integer getStudentAge() { return studentAge; } public void setStudentAge(Integer studentAge) { this.studentAge = studentAge; } public Date getStudentBirthday() { return studentBirthday; } public void setStudentBirthday(Date studentBirthday) { this.studentBirthday = studentBirthday; } @Override public String toString() { return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentAge=" + studentAge + ", studentBirthday=" + studentBirthday + "]"; }}Copy the code

Here’s a summary of the commonly used annotation tags in JPA

  • @Entity: The @Entity tag is above the class name and serves as the identity of the Entity class.
  • @table: If the name of the Entity class is different from the name of the database Table that maps to it, use the @table annotation. The annotation is consistent with the @Entity annotation

Can be written on a separate statement line or on the same line as the declaration statement. The common option for the @TABLE annotation is name, which specifies the Table name of the database. The @TABLE annotation also has two options catalog and Schema that set the database catalog or schema to which the Table belongs, usually the database name. The uniqueConstraints option is used to set the constraint and normally does not need to be set.

  • @ID: @ID sets the object representation that identifies the entity class whose attributes map to the primary key in the table.
  • @GeneratedValue: Sets the policy for generating identifiers. This is often used with @id. Parameter: strategy Specifies the specific build strategy
    • @generatedValue (strategy=GenerationType.AUTO) is the default policy. Similar to Hibernate’s Native strategy, the generation depends on the underlying database.
    • @generatedValue (strategy = GenerationType.identity) specifies the automatic growth policy for MySQL;
    • Three: @generatedValue (Strategy = GenerationType.SEQUENCE, generator = “seq_tbl_person”) Generator indicates the name of the generator. Also specify @sequenceGenerator (name = “seq_tbl_person”, sequenceName = “seq_tbl_person”, allocationSize

= 1) Use with annotations. Where name specifies the name of the generator (the same as the value of the generator), sequenceName specifies the name of the sequence defined in the database, and allocationSize specifies that the sequence grows by one at a time.

  • Column: Describes the definition of the Column in the database table, with the following properties.
    • Name: indicates the name of the field in the database table. By default, the attribute names are the same.
    • Nullable: indicates whether the field is allowed to be NULL. The default value is True.
    • Unique: indicates whether the field is unique. The default value is false.
    • Length: indicates the size of the field. This parameter is valid only for String fields.
    • Insertable: indicates whether this field should appear in the -insetrt statement when the ORM framework performs an insert operation. The default is true.
    • Updateable: indicates whether this field should appear in the UPDATE statement when the ORM framework performs an UPDATE operation. The default value 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 column in the database. Usually ORM framework can automatically determine the type of the 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 for String is VARCHAR, which is useful if you want to map the String type to the BLOB or TEXT field type of a particular database.

  • OrderBy: You can specify the order in which the data is loaded.
  • @TRANSIENT: Indicates that this property is not a mapping to a field in a database table and will be ignored by the ORM framework.

If an attribute is not a field mapping of a database table. Be sure to mark it at @Transient. Otherwise. The ORM framework annotates it as @Basic by default


Custom query Statements (JPQL)

This query can be declared in a Repository method, getting rid of the constraints like naming queries and declaring the query directly in the corresponding interface method for a clearer structure, which is unique to SpringDataJpa

Use @Query to customize the Query

  • None of the previous methods used to get the data do not use any HQL(Hibernate Query Language) statements. Those methods are sufficient

Many requirements, and sometimes feel that the method name is too long is not convenient, the following describes the use of Hql to obtain data.

For example, to query student information by specific name, add the following method to the StudentRepository class:

@Query("select s from Student s where s.studentName = ? 1") Student findByStudentName(String studentName);Copy the code

Called in Controller, as follows

/*** * http://localhost:8090/findStudentsByName? Name = Liu 3 * @param name * @return */ @RequestMapping("/findStudentsByName") public Object findStudentBystudentName(String) name) { Student student = repository.findByStudentName(name); return student; }Copy the code

Use of @Query in combination with @modifying

These two annotations are declared together to define a personalized update operation, such as when only certain fields are updated, as shown in the following example:

  • A. To modify the student name, first add the following code under StudentRepository:
@Transactional @Modifying @Query("update Student s set s.studentName=? 1 where s.studentId=? 2") int setFixedStudentNameFor(String studentName,int studentId);Copy the code
  • B. Call the StudentController. The code is as follows:
/*** 
* http://localhost:8090/setStudent?name=lucy&id=2 
* @param name 
* @return */ 
@RequestMapping("/setStudent") 
public Object setStudentByName(String name,int id) { 
    int i = repository.setFixedStudentNameFor(name,id); 
    Map<String,Object> map=new HashMap<String,Object>(); 
    if(i>0) { 
        map.put("success", true); 
    }else {
        map.put("success", false); }return map; 
    }
}
Copy the code

Index parameters and named parameters

  1. The following example shows the index parameters. The index value starts from 1. The number of “X” needs to be the same as the number of parameters defined by the method, and in the same order

Should agree

@Transactional @Modifying @Query("update Student s set s.studentName=? 1 where s.studentId=? 2") int setFixedStudentNameFor(String studentName,int studentId);Copy the code
  1. Named parameters (this is recommended) allow you to define the parameter name and assign with @param (” parameter name “) regardless of order. The following

-a. Add the following code to the StudentRepository:

@Query("select s from Student s where s.studentName like %:studentName% ") 
List<Student> queryByname(@Param(value = "studentName") String studentName);
Copy the code
-b. Call the StudentController. The code is as follows:Copy the code
/*** 
* http://localhost:8090/queryByname?name=刘 
* @param name 
* @return */ 
@RequestMapping("/queryByname") 
public Object queryByname(String name) { 
    List<Student> student = repository.queryByname(name); 
    return student; 
}
Copy the code

Well, that’s the end of the story. You’ll have to do some hands-on work to learn the real thing in the next tutorial — native Sql queries for SpringDataJpa. Come on, ladies and gentlemen


The last

  • For more references, see here:Chen Yongjia’s Blog

  • Like the little friend of the blogger can add a concern, point a like oh, continue to update hey hey!