search
HomeJavajavaTutorialUsing Spring Data JPA to connect to the database in Spring Boot

Using Spring Data JPA to connect to the database in Spring Boot

Oct 17, 2018 pm 04:16 PM
javamysqlspringwindows

The content of this article is about using Spring Data JPA to connect to the database in Spring Boot. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I used to use Mybatis for database development. Recently, after learning Spring Boot, I found that JPA is more friendly, so let’s learn about the principles of JPA together.

Spring Data JPA

A brief introduction to JPA

Java Persistence API (JPA) is a specification of Java. It is used to save data between Java objects and relational databases.
JPA acts as a bridge between object-oriented domain models and relational database systems. Since JPA is just a specification, it does nothing by itself. It requires an implementation. Therefore, ORM tools like Hibernate, TopLink and iBatis implement the JPA data persistence specification.

Spring Data JPA is a set of JPA application frameworks encapsulated by Spring based on the ORM framework and JPA specifications, which allows developers to access and operate data with minimalist code. It provides common functions including adding, deleting, modifying, checking, etc., and is easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency!

Basic query

Spring Data JPA has implemented some basic database operations, including basic addition, deletion, modification and query.

First, you need to introduce relevant dependencies in pom.xml.

    <dependency>
    <groupid>mysql</groupid>
    <artifactid>mysql-connector-java</artifactid>
    </dependency>
    <dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-jpa</artifactid>
    </dependency>

Second, you need to add database-related configuration and jpa-related configuration in the application.properties configuration file

    #配置数据源
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/springboot
    spring.datasource.username=username
    spring.datasource.password=password
    
    #jpa数据库表格创建的方式,和控制台sql的打印
    jpa.hibernate.ddl-auto=update
    jpa.hibernate.show-sql=true

Third, write the entity class.

Under normal circumstances, if we add the annotation @Entity to the entity class, the entity class will be related to the table.
If we don’t need to associate one of the attributes with the database and just do calculations during display, we only need to add the @Transient attribute.

Using Spring Data JPA to connect to the database in Spring Boot

@Id identifies the primary key
@GeneratedValue is the auto-increment method of the specified primary key.

Fourth, write the query method.

Just write an interface to implement the JpaRepository interface:
You need to add two parameters after JpaRepository, one is the entity class, and the other is the type of the primary key.

Using Spring Data JPA to connect to the database in Spring Boot

After inheriting JpaRepository, you can use the simple addition, deletion, modification and search functions.

@Test
public void testBaseQuery() throws Exception {
    Girl girl=new Girl();
    userRepository.findAll();
    userRepository.findOne(1);
    userRepository.save(girl);
    userRepository.delete(girl);
    // ...
}

Customized simple query

Because this can only satisfy our basic query, if we don’t want to follow the query he gave us, do we need to write our own query statement? ? The answer is definitely no. We can still generate some query statements according to JPA rules.

A custom simple query is to automatically generate SQL based on the method name. The main syntax is findXXBy, readAXXBy, queryXXBy, countXXBy, getXXBy followed by the attribute name:

Using Spring Data JPA to connect to the database in Spring Boot

Using Spring Data JPA to connect to the database in Spring Boot

Complex Query

Here we need to write sql ourselves. Let’s take a look at what needs to be paid attention to.
Use the @Query annotation on the SQL query method. If deletion and modification are involved, add @Modifying as needed. You can also add @Transactional support for things, query timeout settings, etc. as needed.

Note: When writing Query, the table name in the HQL statement should be the class name mapped by the ORM.

    //传单个值的时候
    @Query("select u from User u where u.age = ?#{[0]}")
    List<user> findUsersByAge(int age);
    
    //传多个值的时候
    @Query("select u from User u where u.firstname = :#{#customer.firstname}")
    List<user> findUsersByCustomersFirstname(@Param("customer") Customer customer)</user></user>

The above is the detailed content of Using Spring Data JPA to connect to the database in Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools