Spring Boot Best Practices (v) Spring Data JPA Operation MySQL 8

Source: Internet
Author: User

First, Spring Data JPA Introduction

The JPA (Java Persistence API) Java Persistence API is the standard specification for Java persistence, and Hibernate is a technical implementation of the persistence specification, and Spring Data JPA is a framework encapsulated on Hibernate.

Development environment
    • Spring Boot 2.0.4
    • Spring Data JPA 2.0.4
    • MySQL 8.0.12
    • JDK 8
    • Idea 2018.2
    • Windows 10
# # Two, integration steps # # 2.1 configuration relies on adding spring Data JPA and MySQL Connector, configuring the Pom.xml file with the following code: "' XML org.springframework.boot spring-boot-starter-data-jpa 2.0.4.RELEASE mysql mysql-connector-java 8.0.12 "' More JPA version: HTTP://MVNREPOSITORY.COM/ARTIFACT/ORG.SPRINGFRAMEWORK.BOOT/SPRING-BOOT-STARTER-DATA-JPA More MySQL Versions: http://mvnrepository.com/artifact/mysql/mysql-connector-java### 2.2 application.properties Setting configuration file ' xml # # Data Source Configuration spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?servertimezone=utc&usessl=false& allowpublickeyretrieval=truespring.datasource.username=rootspring.datasource.password= 123456spring.datasource.driver-class-name=com.mysql.cj.jdbc.driverspring.jpa.hibernate.ddl-auto= Updatespring.jpa.database-platform=org.hibernate.dialect.mysql5innodbdialectspring.jpa.show-sql=true "- Hbm2ddl.auto: Auto Create | update | Validate database table structure-dialect: Set database engine to INNODB-SHOW-SQL: Print SQL statement, easy to debug Hbm2ddl.auto has four properties:-Create: Every load Hibernate will delete the last generated table, and then build the new table based on your model class, even if there are no changes two times to do so, which is one of the main reasons for the loss of database table data. [Delete-Create-action]-Create-drop: The table is generated according to the model class each time hibernate is loaded, but the table is automatically deleted when Sessionfactory is closed. [Delete-Create-action-delete]-update: The most commonly used property, the first time you load hibernate according to the model class will automatically establish the table structure (if the database is first established), later when loading hibernate according to the model class automatically update the table structure,Even if the table structure changes, the rows in the table still exist, and the previous rows are not deleted. It is important to note that when deployed to a server, the table structure is not immediately established, it is to wait for the application to run for the first time. [No table-Create-action | There is a table-update does not have an attribute column-action]-Validate: Each time hibernate is loaded, validation creates a database table structure that is only compared to tables in the database and does not create new tables, but inserts new values. [Start validation table structure, validation unsuccessful, project start failure]### 2.3 Add entity Class (Entities) ' Java@entitypublic class User implements Serializable {@Id @ Generatedvalue private Long ID; @Column (name = "Name", Nullable = False) private String name; @Column (nullable = false) private int age; @Column (nullable = false) private String pwd; Public user () {} public user (string name, int age, string pwd) {this.name = name; this.age = age; this.pwd = pwd;}//... suddenly Slightly set, get method} '-@GeneratedValue automatically generate id-@Column set column properties (name= "database column name")-@Transient does not map to database # # 2.4 Create Repository Interface Build Business method ' ' Javapublic interface Userrepository extends Jparepository {Public User findbyname (String name);} Inherit jparepository after inheriting:-Repository.save (user); Insert or Save-repository.saveflush (user); Save and Refresh-repository.exists (1)//primary key query exists-repository.findone (1); Primary key Query Single-repository.delete (1); Primary KEY Delete-Repository.findbyusername ("stone"); Query single-repository.findall (pageable); List of queries with sorting and paging-repository.savestate (1, 0); Update a single field These methods, you can do the operation of a table without writing a line of code, of course, you can also extend some of their own methods, just need to add a method in the userrepository. # # # 2.5 Add, Query database ' java@controller@requestmapping ("/") public class Usercontroller {@Autowired private userrepository Userrepository; @RequestMapping ("/") public Modelandview Index () {Userrepository.save (New User ("Lao Wang", 18, "123456")); Modelandview Modelandview = new Modelandview ("/index"); Modelandview.addobject ("DataSize", Userrepository.findall (). Size ()); return modelandview; }} ' So far, the integrated Spring Data JPA is all done, start debugging, and see how it works. In Application.properties configurationThe database engine is innodb:> spring.jpa.database-platform=org.hibernate.dialect.mysql5innodbdialect step two, Identify transaction @transactional sample code on a method or class: ' @Transactionalpublic void Savegroup () {userrepository.save (user); Userrepository.save (user2);} "If an error occurs, the transaction is rolled back." # # # # # # # 3.1.2 Transaction does not take effect ##### 3.1.2.1 confirm that the database engine is in Application.properties configuration database engine for innodb:> spring.jpa.database-platform= org.hibernate.dialect.mysql5innodbdialect##### 3.1.2.2 View table engine must be innodb through command:> Show table status from mytestdb;! [] (Http://icdn.apigo.cn/blog/mysql-select-table.png) modify the table Engine:> ALTER TABLE table_name engine=innodb;##### 3.1.2.3 Note the namespaces that introduce @transactional @transactional annotations come from org.springframework.transaction.annotation packages, not javax.transaction.### 3.2 automatically generated by name SQLJPA supports the method of automatically generating SQL queries based on simple keywords, such as the combination of name and age, the code is as follows:> public User findbynameandage (String name,int Age), use the keyword "and", or query the time interval of the:> public User findbystartdatebetween (long startdate); Use the keyword "between". More internal support keywords, such as the following table: | Keyword | Sample | JPQL Snippet | | ------------------- | -------------------------------------- | ------------------------------------------------------------ || and | Findbylastnameandfirstname | ... where x.lastname =? 1 and x.firstname =? 2 | | Or | Findbylastnameorfirstname | ... where x.lastname =? 1 or x.firstname =? 2 | | Is,equals | Findbyfirstname,findbyfirstnameis | ... where x.firstname =? 1 | | Between | Findbystartdatebetween | ... where x.startdate between? 1 and? 2 | | LessThan | Findbyagelessthan | ... where X.age <? 1 | | lessthanequal | findbyagelessthanequal | ... where x.age <=? 1 | | GreaterThan | Findbyagegreaterthan | ... where x.age >? 1 | | greaterthanequal | findbyagegreaterthanequal | ... where x.age >=? 1 | | After | Findbystartdateafter | ... where x.startdate >? 1 | | Before | Findbystartdatebefore | ... where X.startdate <? 1 | | IsNull | Findbyageisnull | ... where x.age is null | | Isnotnull,notnull | Findbyage (IS) notnull | ... where x.age not NULL | | Like | Findbyfirstnamelike | ... where x.firstname like? 1 | | Notlike | Findbyfirstnamenotlike | ... where x.firstname not like? 1 | | Startingwith | Findbyfirstnamestartingwith | ... where x.firstname like? 1 (parameter bound with appended%) | | Endingwith | Findbyfirstnameendingwith | ... where x.firstname like? 1 (parameter bound with prepended%) | | containing | findbyfirstnamecontaining | ... where x.firstname like? 1 (parameter bound wrapped in%) | | | Findbyageorderbylastnamedesc | ... where x.age =? 1 order BY x.lastname desc | | Not | Findbylastnamenot | ... where x.lastname <>? 1 | | In | Findbyagein (Collection Ages) | ... where x.age in? 1 | | Notin | Findbyagenotin (Collection Ages) | ... where x.age not in? 1 | | True | Findbyactivetrue () | ... where x.active = True | | False | Findbyactivefalse () | ... where x.active = False | | IgnoreCase | Findbyfirstnameignorecase | ... where UPPER (x.firstame) = UPPER (? 1) | Official document: https://docs.spring.io/spring-data/jpa/docs/2.0.9.RELEASE/reference/ html/#jpa. repositories### 3.3 Custom SQL statement queries are also well supported for users to write sql,spring Boot JPA themselves, just add @query (SQL). Example code: "' Java@traNsactional@modifying@query ("Update User set name=?1 where id=?2") public int modifyname (String name,long ID); Note: @modifying annotations must be added when performing the modification and deletion, and the ORM knows that to perform the write operation, update/delete query must also need to add @transactional (transaction) for normal operation. # # Iv. Common errors in the use of Spring Data JPA, you may encounter some of the following errors. # # # 1.No default constructor for entity class entities do not have null parameters for the defaults constructor, new can be resolved. # # # 2.java.sql.sqlexception:access denied for user ' @ ' 172.17.0.1 ' (using Password:no) Startup Project error, username and password configuration key is wrong, MYSQL8 user name and password configuration is not the same as before, MySQL 8 correct username password is configured as follows: "' spring.datasource.username=rootspring.datasource.password=123456# The following is a configuration of the old database driver configuration #spring.datasource.data-username=root#spring.datasource.data-password=123456 ' # # 3.Caused by: Java.lang.IllegalStateException:Cannot Load Driver Class:com.mysql.jdbc.DriverMySQL 8 The Spring.datasource.driver-class-name configuration needs to be changed to "Com.mysql.cj.jdbc.Driver" instead of "Com.mysql.jdbc.Driver", properly configured as follows: " Spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver ""

Spring Boot Best Practices (v) Spring Data JPA Operation MySQL 8

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.