• Question: How do I use SpringDataJPA?

First, investigate the target

  • Use of SpringDataJPA

Second, topic analysis

Steps to use Spring Data JPA (implementation details below)

  • 1. Create a Maven project and import the dependency

  • 2. Add the configuration

  • 3. Add annotations to entity classes

  • 4. Write dao interfaces

  • 5. Write test classes

Three, application scenarios

  • Spring Data JPA is a specific implementation of THE JPA specification in the encapsulation, Hibernate framework is the specific implementation of JPA specification.

Four,

The main investigation is:

  • 1. Environment construction of Spring Data JPA
  • 2. Common annotations for Spring Data JPA
  • 3. Dao writing requirements of Spring Data JPA

Where spring Data JPA usage steps

First, look at the structure of the project Click to go to the video learning website

1. Import dependencies

  • Import the following dependencies in the POM.xml file
<? The 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" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > cn. Itcast < / groupId > < artifactId > jpa - day2 < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < properties > < spring. The version > 5.0.2. RELEASE < / spring. Version > < hibernate version > 5.0.7. Final < / hibernate. Version > < slf4j. Version > 1.6.6 < / slf4j version > < log4j version > 1.2.12 < / log4j version > < c3p0. Version > 0.9.1.2 < / c3p0 version > < mysql. Version > 5.1.6 < / mysql version > </properties> <dependencies> <! <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <! --spring beg --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> < version > 1.6.8 < / version > < / dependency > < the dependency > < groupId > org. Springframework < / groupId > <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <! <dependency> <groupId>org.springframework</groupId> <artifactId> Spring-orm </artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <! -- spring end--> <! -- hibernate beg --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> < the groupId > org. Hibernate < / groupId > < artifactId > hibernate validator - < / artifactId > < version > 5.2.1. The Final < / version > </dependency> <! -- hibernate end--> <! -- c3p0 beg --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0.version}</version> </dependency> <! -- c3p0 end --> <! -- log end --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <! -- log end --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <! <dependency> <groupId>org.springframework.data</groupId> < artifactId > spring - data - jpa < / artifactId > < version > 1.9.0. RELEASE < / version > < / dependency > < the dependency > <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <! <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> < version > 2.2.4 < / version > < / dependency > < the dependency > < groupId > org. Anyone. Web < / groupId > < artifactId > javax.mail. El < / artifactId > < version > 2.2.4 < / version > < / dependency > <! -- el end --> </dependencies> </project>Copy the code

2. The configuration

  • Configure the following information in the applicationContext.xml file
<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <! Spring and Spring Data jPA configuration --> <! <bean id ="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> <! <property name="packagesToScan" value="cn.itcast.domain"/> <! - the jpa implementation factory - > < property name = "persistenceProvider" > < bean class = "org. Hibernate, jpa HibernatePersistenceProvider" / > </property> <! <property name="jpaVendorAdapter"> <bean class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="generateDdl" value="false" /> <! Property name="database" value="MYSQL" /> <! -- Database dialect: Support special grammar -- > < property name = "databasePlatform" value = "org. Hibernate. The dialect. MySQLDialect" / > < property name = "showSql" value="true"/> </bean> </property> <! -- JPA dialect: Advanced features - > < property name = "jpaDialect" > < bean class = "org. Springframework. Orm. Jpa. Vendor. HibernateJpaDialect" / > </property> </bean> <! - 2. Create a database connection pool -- -- > < bean id = "dataSource" class = "boPooledDataSource com.mchange.v2.c3p0.Com" > < property name = value = "user" "root"/> <property name="password" value = "root"/> <property name="jdbcUrl" value="jdbc:mysql:///jpa"/> <property name="driverClass" value="com.mysql.jdbc.Driver"/> </bean> <! < jPA: Repositoriesesrepositories base-package="cn.itcast.dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactoty"></jpa:repositories> <! - 4. Configuration transaction manager - > < bean id = "transactionManager" class = "org. Springframework. Orm. Jpa. JpaTransactionManager" > < property name="entityManagerFactory" ref = "entityManagerFactoty"></property> </bean> <! - 5. Declarative transactions --> <! <context:component-scan base-package="cn.itcast"></context:component-scan> </beans>Copy the code

3. Add annotations to entity classes

package cn.itcast.domain; import javax.persistence.*; /** * Client entity class * configures mapping relationship * 1. Entity class and table mapping relationship * 2. * @entity: declare the Entity class * @table: configure the mapping between the Entity class and the Table * name: */ @entity@table (name = "cST_customer ") public class Customer {/** * @id: declare primary key configuration * @generatedValue: * strategy * generationType. IDENTITY: * generationType. SEQUENCE: * generationtype. SEQUENCE * generationtype. SEQUENCE: * GenerationType.TABLE: jPA provides a mechanism for primary key increment in the form of a database TABLE. The program automatically helps us select the primary key generation policy * @column: configure the mapping between attributes and fields * name: */ @id @GeneratedValue(Strategy = GenerationType.identity) @column (name = "CUST_ID ") private Long custId; // The primary key @column (name = "cust_NAME ") private String custName; @column (name = "CUST_SOURCE ") private String custSource; // Customer source @column (name = "cust_level") private String custLevel; // Customer level @column (name = "CUST_industry ") private String custIndustry; @column (name = "CUST_phone ") private String custPhone; @column (name = "CUST_address ") private String custAddress; Public long getCustId() {return custId; } public void setCustId(long custId) { this.custId = custId; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustSource() { return custSource; } public void setCustSource(String custSource) { this.custSource = custSource; } public String getCustLevel() { return custLevel; } public void setCustLevel(String custLevel) { this.custLevel = custLevel; } public String getCustIndustry() { return custIndustry; } public void setCustIndustry(String custIndustry) { this.custIndustry = custIndustry; } public String getCustPhone() { return custPhone; } public void setCustPhone(String custPhone) { this.custPhone = custPhone; } public String getCustAddress() { return custAddress; } public void setCustAddress(String custAddress) { this.custAddress = custAddress; } @Override public String toString() { return "Customer{" + "custId=" + custId + ", custName='" + custName + '\'' + ", custSource='" + custSource + '\'' + ", custLevel='" + custLevel + '\'' + ", custIndustry='" + custIndustry + '\'' + ", custPhone='" + custPhone + '\'' + ", custAddress='" + custAddress + '\'' + '}'; }}Copy the code

4. Write Dao interfaces

package cn.itcast.dao; import cn.itcast.domain.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import java.util.List; /** * Compliance with SpringDataJpa DAO layer interface specification * JpaRepository< entity class type of operation, The type of primary key in the entity class > * * encapsulates basic CRUD operations * JpaSpecificationExecutor< entity class type of the operation > * * encapsulates complex queries (paging) */ Public Interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {/** * from Customer where custName = ? * * Configure the JPQL statement with the @query annotation */ @query (value = "From Customer where custName =?" ) public Customer findJpql(String custName); * JPQL: from Customer where custName =? and custId = ? * * For multiple placeholder arguments *, by default, the position of the placeholder argument must be the same as the position of the method argument * * can be specified. */ @query (value = "from Customer where custName =? 2 and custId = ? 1") public Customer findCustNameAndId(Long id, String name); SQL :update cST_customer set CUST_name =? SQL: Update cST_customer set CUST_name =? where cust_id = ? * jpql :update Customer set custName = ? where custId = ? * * @query: represents when a Query is performed * * the method is declared to perform an update * @modifying * * The current update operation is performed */ @query (value = "update Customer set custName =? 2 where custId = ? 1") @Modifying public void updateCustomer(long custId, String custName); SQL: select * from cst_customer * Query: configure SQL Query * value: SQL statement * nativeQuery: Query method * true: SQL query * false: @query (value = "select * from cst_customer", nativeQuery = true) @Query(value = "select * from cst_customer where cust_name like ? 1", nativeQuery = true) public List<Object []> findSql(String name); /** * Convention for method name * findBy: Query * Attribute name in object (uppercase) : query condition * CustName ** Default: FindByCustName -- query by customer name * * findBy from XXX (entity class) * attribute name is resolved by method name during springdataJpa run time Where custName = * 1. FindBy + attribute name (according to the attribute name select complete matching query = * 2. The findBy + attribute name + "query mode (Like | isnull)" * findByCustNameLike * 3. Many conditions findBy query * + attribute name + "query" + "condition of the connector (and | or)" + attribute name + "query" * / public Customer findByCustName (String custName); public List<Customer> findByCustNameLike(String custName); / / use the Customer name and fuzzy matching Customer by sector precise matching query public Customer findByCustNameLikeAndCustIndustry (String custName, String custIndustry); }Copy the code

Test cases

package cn.itcast.test; import cn.itcast.dao.CustomerDao; import cn.itcast.domain.Customer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "Classpath: applicationContext. XML") / / specify the spring container configuration information public class CustomerDaoTest {@autowired private CustomerDao customerDao; @test public void testFindOne(){Customer Customer = customerDao.findone (3L); System.out.println(customer); } /** * sava : Save or update * depending on whether the passed object has a primary key ID, * if there is no ID primary key attribute: */ @test public void testSave() {Customer Customer = new Customer(); Customer.setcustname (" Dark horse programmer "); customer.setCustLevel("vip"); Customer. SetCustIndustry (" it education "); customerDao.save(customer); } @Test public void testUpdate() { Customer customer = new Customer(); customer.setCustId(4l); Customer.setcustname (" Dark horse programmer is good "); customerDao.save(customer); } @Test public void testDelete() { customerDao.delete(3L); } @Test public void testFindAll() { List<Customer> list = customerDao.findAll(); for (Customer customer : list) { System.out.println(customer); @test public void testCount() {long count = customerDao.count(); System.out.println(count); } /** * test: check whether the customer whose ID is 4 exists * 1. Check whether the customer whose ID is 4 exists * 1. If the value is empty, it does not exist. Check the number of customers in the database whose ID is 4. * If the number is 0, it does not exist. If the number is greater than 0, it exists. System.out.println(" does a client with id 4 exist: "+ exists); } /** * Transactional: * @transactional: ** findOne: * em.find() : load immediately * getOne: * em. GetReference: Lazy loading * * returns when the client's dynamic proxy object * * is used, */ @test@transactional public void testGetOne() {Customer Customer = CustomerDao.getone (4l); System.out.println(customer); }}Copy the code

JPQL test case

package cn.itcast.test; import cn.itcast.dao.CustomerDao; import cn.itcast.domain.Customer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "Classpath: applicationContext. XML") / / specify the spring container configuration information public class JpqlTest {@autowired private CustomerDao CustomerDao;  @test public void testFindJPQL() {Customer Customer = customerDao.findjpQL ("传智 的 podcasts "); System.out.println(customer); {} @ Test public void testFindCustNameAndId () the Customer the Customer = customerDao. FindCustNameAndId (1 l, "the wisdom podcast"); System.out.println(customer); } /** * Test JPQL update operation ** springDataJpa update/delete operation with JPQL ** need to manually add transaction support ** Default to execute after completion of transaction * @rollback: Set whether an automatic Rollback * false | true * / @ Test @ Transactional / / add transaction support @ the Rollback (value = false) public void testUpdateCustomer () { CustomerDao. UpdateCustomer (4 l, "dark horse programmer"); @test public void testFindSql() {List<Object[]> List = customerDao.findsql (" customerDao %"); for (Object[] obj : list) { System.out.println(Arrays.toString(obj)); }} / / Test method naming queries @ Test public void testNaming () {Customer Customer = customerDao. FindByCustName (" preach wisdom podcast "); System.out.println(customer); } @test public void testFindByCustNameLike() {List<Customer> List = CustomerDao. FindByCustNameLike (" preach wisdom podcast % "); for (Customer customer : list) { System.out.println(customer); }} / / Test method naming queries @ Test public void testFindByCustNameLikeAndCustIndustry () {Customer Customer = CustomerDao. FindByCustNameLikeAndCustIndustry (" wisdom podcast % ", "it education"); System.out.println(customer); }}Copy the code

If you feel there is a harvest, you might as well take a few seconds to click a like, welcome to follow my public accountPlay programming crypto, currently specializing in writing Java related, data structures and algorithms and computer fundamentals.