使用JPA和JSF在连接表中保留数据

时间:2015-01-12 12:08:43

标签: mysql jsf java-ee jpa jboss

我的模型包含类StudentCourse(见下文)。

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

正如您所看到的,JPA会自动创建连接表StudentCourse。我现在希望能够将已创建且已保留的Courses添加到已创建并保留Student的内容中,以便Students可以包含任意数量的Courses,他们访问。引用将存储在我的MySQL数据库的StudentCourse表中。

我在JSF中坚持Courses(例如)的方式是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <link rel="stylesheet" href="style.css" type="text/css" />
        <title><ui:insert name="title">Title</ui:insert></title>
    </h:head>

    <h:body>
        <div id="header">
            <ui:insert name="header">
            </ui:insert>
        </div>

        <div id="content">
            <ui:insert name="content">
                <h:form>
                    <p:messages id="messages" showDetail="true" autoUpdate="true"
                                closable="true" />
                    <p:panel id="grid" header="#{msg.course}:"
                             style="margin-bottom:10px;">
                        <h:panelGrid columns="2" cellpadding="5">
                            <p:outputLabel value="#{msg.name}:" for="name" />
                            <h:panelGroup>
                                <p:inputText value="#{courseController.course.name}" id="name"
                                             required="true" />
                            </h:panelGroup>
                            <p:outputLabel value="#{msg.cp}:" for="cp" />
                            <h:panelGroup>
                                <p:inputText value="#{courseController.course.cp}" id="cp"
                                             required="true">
                                    <f:validateLength minimum="1" maximum="2" />
                                </p:inputText>
                            </h:panelGroup>
                        </h:panelGrid>
                    </p:panel>
                    <p:commandButton action="#{navigationController.openStudentList()}"
                                     value="#{msg.cancel}" immediate="true" icon="ui-icon-circle-close" />
                    <p:commandButton action="#{courseController.saveCourse()}"
                                     value="#{msg.save}" update="grid" icon="ui-icon-circle-check" />
                </h:form>
            </ui:insert>
        </div>

        <div id="footer">
            <ui:insert name="footer">
            </ui:insert>
        </div>

    </h:body>
</html>

如何使用我的Course为已创建的Student保留已创建的StudentController以及如何通过JSF执行此操作,我使用{{1}进行了此操作在我的例子中?

0 个答案:

没有答案