使用JPA和JSF保持连接表

时间:2015-01-11 17:40:18

标签: java hibernate jsf java-ee jpa

我的模型包含学生课程(见下文)。

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
}

Course.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
}

控制器如下所示。

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应用程序中添加,删除和编辑学生课程

正如您所见,JPA会自动创建连接表 StudentCourse 。我现在希望能够将已创建和持久的课程添加到已创建并保留学生,以便学生可以在任何数字中注册课程。该引用将存储在我的MySQL数据库的 StudentCourse 表中。

创建连接表是一个好主意,还是应该创建模型类 StudentCourse 和控制器 StudentCourseController 来实现此问题?

1 个答案:

答案 0 :(得分:1)

对于你的问题所描述的连接表就足够了但是如果你以后想要添加他们得到的等级之类的属性那么你将需要一个额外的实体类来建模关系。