Home Java javaTutorial Using 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
java mysql spring windows

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>
Copy after login

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
Copy after login

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);
    // ...
}
Copy after login

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>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
MySQL vs. phpMyAdmin: Understanding the Key Differences MySQL vs. phpMyAdmin: Understanding the Key Differences May 06, 2025 am 12:17 AM

MySQL is a database management system, and phpMyAdmin is a web tool for managing MySQL. 1.MySQL is used to store and manage data and supports SQL operations. 2.phpMyAdmin provides a graphical interface to simplify database management.

Python development_python installation Python development_python installation May 07, 2025 pm 04:33 PM

Python can run on a variety of platforms, including our common ones: Windows, Unix, Linux, and Macintosh. This article will introduce in detail the process of installing Python in Windows operating system. My operating system is Windows 7, 32-bit version. When installing Python, we can choose to install it from the source code or select the already compiled binary version for installation. I chose the latter here. Step 1 Download the installation package. We download the installation package of Python from the official Python website: http://www.python.org. The version I selected is: python-3.3.2.msi click to download, I

MySQL: A Practical Application of SQL MySQL: A Practical Application of SQL May 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

10 latest tools for web developers 10 latest tools for web developers May 07, 2025 pm 04:48 PM

Web development design is a promising career field. However, this industry also faces many challenges. As more businesses and brands turn to the online marketplace, web developers have the opportunity to demonstrate their skills and succeed in their careers. However, as demand for web development continues to grow, the number of developers is also increasing, resulting in increasingly fierce competition. But it’s exciting that if you have the talent and will, you can always find new ways to create unique designs and ideas. As a web developer, you may need to keep looking for new tools and resources. These new tools and resources not only make your job more convenient, but also improve the quality of your work, thus helping you win more business and customers. The trends of web development are constantly changing.

MySQL vs. Oracle: Licensing, Features, and Benefits MySQL vs. Oracle: Licensing, Features, and Benefits May 08, 2025 am 12:05 AM

The main difference between MySQL and Oracle is licenses, features, and advantages. 1. License: MySQL provides a GPL license for free use, and Oracle adopts a proprietary license, which is expensive. 2. Function: MySQL has simple functions and is suitable for web applications and small and medium-sized enterprises. Oracle has powerful functions and is suitable for large-scale data and complex businesses. 3. Advantages: MySQL is open source free, suitable for startups, and Oracle is reliable in performance, suitable for large enterprises.

phpMyAdmin's Function: Interacting with MySQL (SQL) phpMyAdmin's Function: Interacting with MySQL (SQL) May 07, 2025 am 12:16 AM

phpMyAdmin simplifies MySQL database management through the web interface. 1) Create databases and tables: Use graphical interface to operate easily. 2) Execute complex queries: such as JOIN query, implemented through SQL editor. 3) Optimization and best practices: including SQL query optimization, index management and data backup.

.NET Core Quick Start Tutorial 1. The beginning: Talking about .NET Core .NET Core Quick Start Tutorial 1. The beginning: Talking about .NET Core May 07, 2025 pm 04:54 PM

1. The Origin of .NETCore When talking about .NETCore, we must not mention its predecessor .NET. Java was in the limelight at that time, and Microsoft also favored Java. The Java virtual machine on the Windows platform was developed by Microsoft based on JVM standards. It is said to be the best performance Java virtual machine at that time. However, Microsoft has its own little abacus, trying to bundle Java with the Windows platform and add some Windows-specific features. Sun's dissatisfaction with this led to a breakdown of the relationship between the two parties, and Microsoft then launched .NET. .NET has borrowed many features of Java since its inception and gradually surpassed Java in language features and form development. Java in version 1.6

How to return the previous version of win11 win11 system rollback operation guide How to return the previous version of win11 win11 system rollback operation guide May 07, 2025 pm 04:21 PM

Starting the rollback function on Windows 11 must be performed within 10 days after the upgrade. The steps are as follows: 1. Open "Settings", 2. Enter "System", 3. Find the "Recover" option, 4. Start rollback, 5. Confirm the rollback. After rollback, you need to pay attention to data backup, software compatibility and driver updates.

See all articles