search
HomeJavajavaTutorialJava development: How to use JPA for database query and persistence

Java development: How to use JPA for database query and persistence

Java development: How to use JPA for database query and persistence

JPA (Java Persistence API) is a set of tools defined in the Java EE specification for managing database persistence. API. It provides an object-oriented way to perform database operations, allowing developers to more easily perform database queries and data persistence. This article will introduce how to use JPA for database query and persistence, and provide detailed code examples.

Use JPA for database query
Before using JPA for database query, we need to define the entity class and the mapping relationship between the entity class and the database table. The following is the code of an example entity class:

@Entity
@Table(name = "t_student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private Integer age;

    // getters and setters
}

In the above code, the JPA annotation @Entity is used to indicate that the class is an entity class, and @Table specifies the corresponding database table name, @Id and @ GeneratedValue is used to specify the primary key and automatic generation strategy, and @Column is used to specify the mapped database column.

Next, we can use the EntityManager object to perform database queries. The following is a sample code for querying student information based on ID:

public Student findStudentById(Long id) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    return entityManager.find(Student.class, id);
}

In the above code, the query operation is performed by calling the find method of the entityManager object and passing in the entity class and ID. The returned result is the queried entity object.

In addition to querying based on id, JPA also provides rich query syntax and methods, which can be queried based on conditions. The following is a sample code for querying student information based on name:

public List<Student> findStudentsByName(String name) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Student> criteriaQuery = criteriaBuilder.createQuery(Student.class);

    Root<Student> root = criteriaQuery.from(Student.class);
    criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("name"), name));

    TypedQuery<Student> query = entityManager.createQuery(criteriaQuery);
    return query.getResultList();
}

In the above code, by using CriteriaQuery, CriteriaBuilder and other classes, we can construct complex query statements. In the example, we query the student information that meets the conditions through the passed in name parameter.

Use JPA for data persistence
Before using JPA for data persistence, you also need to define the entity class and the mapping relationship between the entity class and the database table. The following is an example of code that persists student information to the database:

public void saveStudent(Student student) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();

    try {
        transaction.begin();
        entityManager.persist(student);
        transaction.commit();
    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        entityManager.close();
    }
}

In the above code, we first obtain the transaction object through the getTransaction method of the entityManager object. The entity object is then persisted to the database by calling the persist method. Finally, the transaction commit and rollback operations are performed in the try-catch-finally block.

In addition to insert operations, JPA also provides update and delete operations. The following is an example code for updating student information:

public void updateStudent(Student student) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();

    try {
        transaction.begin();
        entityManager.merge(student);
        transaction.commit();
    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        entityManager.close();
    }
}

In the above code, we use the merge method to update student information.

Summary
This article introduces how to use JPA for database query and persistence, and provides detailed code examples. By using JPA, developers can perform database operations more easily and improve development efficiency. Of course, JPA has many other functions and features, and I hope readers can learn more about them and use them flexibly.

The above is the detailed content of Java development: How to use JPA for database query and persistence. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.