Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
2
Indexable
package org.example.repository;

import org.example.entity.Student;

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

public class StudentRepo {
    private EntityManagerFactory emf;
    private EntityManager entityManager;

    public StudentRepo() {
        emf = Persistence.createEntityManagerFactory("default");
        entityManager = emf.createEntityManager();
    }

    public void saveStudent(Student student) {
        entityManager.getTransaction().begin();
        entityManager.persist(student);
        entityManager.getTransaction().commit();
    }

    public Student getStudentById(int id) {
        return entityManager.find(Student.class, id);
    }

    public List getAllStudents() {
        Query query = entityManager.createQuery("SELECT s FROM Student s");
        return query.getResultList();
    }

    public void updateStudent(Student student) {
        entityManager.getTransaction().begin();
        entityManager.merge(student);
        entityManager.getTransaction().commit();
    }

    public void deleteStudent(Student student) {
        entityManager.getTransaction().begin();
        entityManager.remove(student);
        entityManager.getTransaction().commit();
    }
}