java - 使用 JPA 和 JSF 保留连接表

标签 java hibernate jsf jakarta-ee jpa

我的模型包含类学生类(class)(见下文)。

Student.java:

@NamedQueries({ @NamedQuery(name = "SelectStudents", query = "SELECT s FROM Student s"), })
@Entity
public class Student implements Serializable {

    private static final long serialVersionUID = -8776005542073703016L;

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

    @Size(min = 3, max = 30)
    private String firstName;

    @Size(min = 3, max = 30)
    private String lastName;

    @Temporal(TemporalType.DATE)
    @Past
    private Date dateOfBirth;

    private String email;

    @Size(min = 5, max = 5)
    private String regNr;

    private String faculty;

    @ManyToMany
    @JoinTable(name = "StudentCourse", joinColumns = { 
            @JoinColumn(name = "student_id", referencedColumnName = "id") }, inverseJoinColumns = { 
            @JoinColumn(name = "course_id", referencedColumnName = "id") })
    private List<Course> courses;

    public Student() {
    }

    // getter and setter
}

类(class).java:

@NamedQueries({
        @NamedQuery(name = "SelectCourses", query = "SELECT c FROM Course c"),
        @NamedQuery(name = "SelectStudentCoursesByName", query = "SELECT c FROM Course c WHERE c.name = :name") })
@Entity
public class Course implements Serializable {

    private static final long serialVersionUID = -5955154651849644853L;

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

    private String name;

    private int cp;

    public Course() {
    }
    // getter and setter
}

Controller 如下所示。

StudentController.java:

@ManagedBean(name = "studentController")
@SessionScoped
public class StudentController {

    private DataModel<Student> students;

    private Student student = new Student();

    @Resource
    private UserTransaction utx;

    @PersistenceContext
    private EntityManager em;

    @PostConstruct
    public void init() {
        students = new ListDataModel<Student>();
        students.setWrappedData(em.createNamedQuery("SelectStudents")
                .getResultList());
    }

    public String newStudent() {
        this.student = new Student();
        return "newStudent?faces-redirect=true";
    }

    public String saveStudent() {
        try {
            utx.begin();
        } catch (NotSupportedException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        student = em.merge(student);
        em.persist(student);
        students.setWrappedData(em.createNamedQuery("SelectStudents")
                .getResultList());
        try {
            utx.commit();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (RollbackException e) {
            e.printStackTrace();
        } catch (HeuristicMixedException e) {
            e.printStackTrace();
        } catch (HeuristicRollbackException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        return "studentList";
    }

    public String deleteStudent() {
        try {
            utx.begin();
        } catch (NotSupportedException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        student = students.getRowData();
        // Transaktionsbeginn
        student = em.merge(student);
        em.remove(student);
        students.setWrappedData(em.createNamedQuery("SelectStudents")
                .getResultList());
        try {
            utx.commit();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (RollbackException e) {
            e.printStackTrace();
        } catch (HeuristicMixedException e) {
            e.printStackTrace();
        } catch (HeuristicRollbackException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        return "studentList?faces-redirect=true";
    }

    public String editStudent() {
        student = students.getRowData();
        return "newStudent";
    }
    // getter and setter
}

CourseController.java:

@ManagedBean
@SessionScoped
public class CourseController {

    private DataModel<Course> courses;

    private Course course;

    @Resource
    private UserTransaction utx;

    @PersistenceContext
    private EntityManager em;

    @PostConstruct
    public void init() {
        courses = new ListDataModel<Course>();
        courses.setWrappedData(em.createNamedQuery("SelectCourses")
                .getResultList());
    }

    public String newCourse() {
        this.course = new Course();
        return "newCourse?faces-redirect=true";
    }

    public String saveCourse() {
        try {
            utx.begin();
        } catch (NotSupportedException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        course = em.merge(course);
        em.persist(course);
        courses.setWrappedData(em.createNamedQuery("SelectCourses")
                .getResultList());
        try {
            utx.commit();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (RollbackException e) {
            e.printStackTrace();
        } catch (HeuristicMixedException e) {
            e.printStackTrace();
        } catch (HeuristicRollbackException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        return "courseList?faces-redirect=true";
    }

    public String deleteCourse() {
        try {
            utx.begin();
        } catch (NotSupportedException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        course = courses.getRowData();
        // Transaktionsbeginn
        course = em.merge(course);
        em.remove(course);
        courses.setWrappedData(em.createNamedQuery("SelectCourses")
                .getResultList());
        try {
            utx.commit();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (RollbackException e) {
            e.printStackTrace();
        } catch (HeuristicMixedException e) {
            e.printStackTrace();
        } catch (HeuristicRollbackException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        return "courseList?faces-redirect=true";
    }

    public String editCourse() {
        course = courses.getRowData();
        return "newCourse?faces-redirect=true";
    }
    // getter and setter
}

我已经创建了 JSF 页面,并且可以在 Java EE 应用程序中添加、删除和编辑学生类(class)

如您所见,连接表StudentCourse是由JPA自动创建的。我现在希望能够将已创建和保留的类(class)添加到已创建和保留的学生,以便学生可以注册任意数量类(class)。该引用将存储在我的 MySQL 数据库的 StudentCourse 表中。

创建联接表是个好主意还是应该创建模型类 StudentCourse 和 Controller StudentCourseController 来实现问题?

最佳答案

对于您的问题所描述的内容,连接表就足够了,但是如果您稍后想要添加属性(例如他们获得的成绩),那么您将需要一个额外的实体类来建模关系。

关于java - 使用 JPA 和 JSF 保留连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27890096/

相关文章:

java - 简单的jpa问题

java - m2eclipse 工件搜索如何工作?

java - 如何将带有数组值的私有(private)二维枚举传递给另一个类?

java - 无法阻止 Hibernate 将日志写入控制台(log4j.properties 可以)

java - 在 JPA 环境中声明 Hibernate 事件监听器

java - Solr 和 postgresql 集成

java - 在 EJB JSF 的一个 session 中存储同步版本的实体

java - JxMaps 可以禁用 Google 的默认 POI

java - 在 JSF 上实现 PRG

jsf - Spring 安全中的ajax