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

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

WBOY
WBOYOriginal
2023-09-21 08:15:391014browse

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