Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Configuration and usage of Spring Data JPA

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about the configuration and use of Spring Data JPA, the editor feels very practical, so share with you to learn, I hope you can get something after reading this article, say no more, follow the editor to have a look.

First of all, the purpose of the SpringData:Spring Data project is to simplify the data access count of building applications based on Spring framework, including non-relational databases, Map-Reduce frameworks, cloud data services, etc.; in addition, it also includes access support for relational databases.

JPA:Java persistence API (JPA) is a Java application program interface specification that describes the management of relational data in applications using the Java Standard Edition platform (Java SE) and the Java Enterprise Edition platform (Java EE). (from Wikipedia)

Now we can talk about Spring Data JPA. From the introduction of Spring Data and JPA, it is not difficult to see that Spring Data JPA is a persistence layer tool that uses the JPA standard. Persistence layer tools, that's interesting. We already have useful persistence layer tools such as Hibernate and Mybatis, so why use Spring Data JPA? This is a good question. Let's take a look at how Spring Data integrates with Spring.

1. Spring integrates Spring Data JPA

1.1 add dependency

Org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java 6.0.6

1.2 configuration Properties

# General data source configuration spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/springboot_jpa?charset=utf8mb4&useSSL=falsespring.datasource.username=rootspring.datasource.password=123456# Hikari data source specific configuration spring.datasource.hikari.maximum-pool-size=20spring.datasource.hikari.minimum-idle=5# JPA related configuration # in SrpingBoot version 2.0, when Hibernate creates data tables, the default database storage engine chooses MyISAM (it seems to be InnoDB before This is rather weird). This parameter is used to switch the default storage engine to InnoDB when creating the table. The spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect# configuration prints out the executed SQL statement information in the log. The spring.jpa.show-sql=true# configuration indicates that the table corresponding to the entity class should be deleted and created when the program starts. This parameter is dangerous because it deletes the corresponding table and rebuilds it. So never use it in a build environment. It can only be used once in a test environment when initializing the database structure. Spring.jpa.hibernate.ddl-auto=update

Students who are interested in spring.jpa.hibernate.ddl-auto attributes can go to the following blog to have a look. Several attribute values of jpa's hibernate.ddl-auto are different.

1.3 create an entity class

Import lombok.Data;import javax.persistence.* / * * @ Description TODO * @ author Raindrop * @ date, 2019-8-22 9:10 * / @ Data / / lombok build Get and Set method @ Entity / / declare this class to be the entity class @ Table (name = "SpringDataJpa") / / the table name corresponding to the entity class public class Test {@ Id / / the attribute is the primary key @ GeneratedValue (strategy = GenerationType.IDENTITY) / / JPA general policy student Creator @ Column (name = "id") / / column name private Integer id in the data table @ Column (name = "username", columnDefinition = "varchar (50) not null") / / column names in the data table and column type private String username; @ Column (name = "email", columnDefinition = "varchar (50) not null") / / column names and column types private String email; @ Column (name = "sex", columnDefinition = "varchar (50) not null") / / column names in the data table and column type private String sex @ Column (name = "age", columnDefinition = "varchar (50) not null") / / column name and column type private String age;} in the data table

1.4 create a dao layer

Well, our preparatory work has been done, and then we can happily carry out CRUD.

Create a Repository class

Package run.halo.app.repository;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import run.halo.app.model.entity.*;import java.util.List;public interface RaindropUserRepository extends JpaRepository {/ / Custom method creates sql statement / / formed SQL statement based on method name: select * from spring_data_jpa where userName =? 1 RaindropUser findByUsername (String userName) / / Custom method creates sql statement based on method name / / SQL statement formed by the method name: select * from spring_data_jpa where sex =? 1 and email=?2 RaindropUser findBySexAndEmail (String sex, String email) / / keep in mind that the use of native JPA uses nativeQuery=true to distinguish whether the native SQL / / the following methods are wrong, can not use the native sql, but if the corresponding entity classes and attributes are used to represent the column and table name / / @ Query ("select id,username from spring_data_jpa where age"

< :age") @Query("select new run.halo.app.model.entity.RaindropUser(raindrop.id," + "raindrop.username,raindrop.email,raindrop.sex," + "raindrop.age) from RaindropUser raindrop where raindrop.age < ?1") List findByLtAge(Integer age);// 该示例也是错的// @Query("select new run.halo.app.model.entity.RaindropUser(a.id,a.username,a.email,a.sex,a.age) from spring_data_jpa a where age >

1 ") / / RaindropUser findByRtAge (Integer age);}

1.5 Test classes

@ Test public void Test () {RaindropUser raindropUser = new RaindropUser (); / / raindropUser.setEmail ("123123@gmail.com"); / / raindropUser.setAge (12); / / raindropUser.setUsername ("Raindrop"); / / raindropUser.setSex ("man"); / / there are some basic methods inherited from the JpaRepository class, which will be explained later. The method is to save data / / raindropUserRepository.save (raindropUser); List list = raindropUserRepository.findByLtAge (15); System.out.println ("List:" + list.get (0)); / / RaindropUser raindropUser1 = raindropUserRepository.findByRtAge (10); / / System.out.println (raindropUser); / / System.out.println (raindropUser1);}

1.6 JAP method analysis

We define findByUsername and findBySexAndEmail methods in the Repository class, and SpringData automatically generates SQL statements to execute based on the method name.

Key words and generated SQL statements

KeywordSampleJPQL snippetAndfindByLastnameAndFirstname... Where x.lastname =? 1 and x.firstname =? 2OrfindByLastnameOrFirstname... Where x.lastname =? 1 or x.firstname =? 2IsMagnum EqualsfindByFirstnameIsFindByFirstnameEquals... Where x.firstname =? 1BetweenfindByStartDateBetween... Where x.startDate between? 1 and? 2LessThanfindByAgeLessThan Where x.age

< ?1LessThanEqualfindByAgeLessThanEqual… where x.age ⇐ ?1GreaterThanfindByAgeGreaterThan… where x.age >

? 1GreaterThanEqualfindByAgeGreaterThanEqual... Where x.age > =? 1AfterfindByStartDateAfter... Where x.startDate >? 1BeforefindByStartDateBefore... Where x.startDate

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report