JPA使用实例

当然,以下是一个更详细的JPA示例代码,涵盖了实体类的关系映射、查询、插入、更新和删除操作:

import javax.persistence.*;

@Entity
@Table(name = "students")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

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

    // Getters and setters
}

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.List;

public class JpaDemo {
    private static final String PERSISTENCE_UNIT_NAME = "myPersistenceUnit";
    private static EntityManagerFactory entityManagerFactory;

    public static void main(String[] args) {
        // 初始化实体管理器工厂
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

        // 创建示例学生对象
        Student student1 = new Student();
        student1.setName("Alice");
        student1.setAge(20);

        Student student2 = new Student();
        student2.setName("Bob");
        student2.setAge(22);

        // 插入示例数据
        insertStudent(student1);
        insertStudent(student2);

        // 查询所有学生
        List<Student> students = getAllStudents();
        System.out.println("All Students:");
        for (Student student : students) {
            System.out.println("ID: " + student.getId() + ", Name: " + student.getName() + ", Age: " + student.getAge());
        }

        // 更新学生信息
        student1.setAge(21);
        updateStudent(student1);

        // 查询单个学生
        Student student = getStudentById(student1.getId());
        System.out.println("Student with ID " + student1.getId() + ":");
        System.out.println("ID: " + student.getId() + ", Name: " + student.getName() + ", Age: " + student.getAge());

        // 删除学生
        deleteStudent(student2);

        // 再次查询所有学生
        students = getAllStudents();
        System.out.println("All Students after deletion:");
        for (Student s : students) {
            System.out.println("ID: " + s.getId() + ", Name: " + s.getName() + ", Age: " + s.getAge());
        }

        // 关闭实体管理器工厂
        entityManagerFactory.close();
    }

    private static EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    private static void insertStudent(Student student) {
        EntityManager entityManager = getEntityManager();
        EntityTransaction transaction = null;
        try {
            transaction = entityManager.getTransaction();
            transaction.begin();
            entityManager.persist(student);
            transaction.commit();
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

    private static List<Student> getAllStudents() {
        EntityManager entityManager = getEntityManager();
        try {
            String query = "SELECT s FROM Student s";
            TypedQuery<Student> typedQuery = entityManager.createQuery(query, Student.class);
            return typedQuery.getResultList();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            entityManager.close();
        }
    }

    private static Student getStudentById(Long id) {
        EntityManager entityManager = getEntityManager();
        try {
            return entityManager.find(Student.class, id);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {


            entityManager.close();
        }
    }

    private static void updateStudent(Student student) {
        EntityManager entityManager = getEntityManager();
        EntityTransaction transaction = null;
        try {
            transaction = entityManager.getTransaction();
            transaction.begin();
            entityManager.merge(student);
            transaction.commit();
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            entityManager.close();
        }
    }

    private static void deleteStudent(Student student) {
        EntityManager entityManager = getEntityManager();
        EntityTransaction transaction = null;
        try {
            transaction = entityManager.getTransaction();
            transaction.begin();
            entityManager.remove(entityManager.contains(student) ? student : entityManager.merge(student));
            transaction.commit();
        } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            ex.printStackTrace();
        } finally {
            entityManager.close();
        }
    }
}

在上述代码中,我们定义了一个Student实体类,并使用注解进行了表和字段的映射。在JpaDemo类中,我们演示了如何使用JPA进行数据操作,包括插入数据、查询数据、更新数据和删除数据。此外,我们还展示了如何获取实体管理器、开启事务、提交事务以及关闭实体管理器工厂。

posted @ 2023-05-30 17:37  田野与天  阅读(41)  评论(0编辑  收藏  举报