如何将数据自动生成到数据库表中,这与使用JSF 2.2和JPA的另一个表有关



我研究JSF 2.2和JPA 2.1

我有两个表格课程和单元这些表格有关系(每个课程可以有很多单元)

课程表有设置单元数的字段

当我使用单元数创建课程时,我想自动生成单元。

我试着这样做,但直到现在我才成功

单位实体类:

@Entity
@Table(catalog = "utechsacademy", schema = "", uniqueConstraints = {
    @UniqueConstraint(columnNames = {"unit_id"})})
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Unit.findAll", query = "SELECT u FROM Unit u"),
    @NamedQuery(name = "Unit.findByCourse", query = "SELECT u FROM Unit u WHERE u.courseId = :courseId"),
    @NamedQuery(name = "Unit.findByUnitId", query = "SELECT u FROM Unit u WHERE u.unitId = :unitId"),
    @NamedQuery(name = "Unit.findByUnitNumber", query = "SELECT u FROM Unit u WHERE u.unitNumber = :unitNumber")})
public class Unit implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "unit_id", nullable = false)
    private Integer unitId;
    @Basic(optional = false)
    @NotNull
    @Column(name = "unit_number", nullable = false)
    private int unitNumber;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "unitId")
    private List<Lesson> lessonList;
    @JoinColumn(name = "course_id", referencedColumnName = "course_id", nullable = false)
    @ManyToOne(optional = false)
    private Course courseId;
    public Unit() {
    }
    public Unit(Integer unitId) {
        this.unitId = unitId;
    }
    public Unit(Integer unitId, int unitNumber) {
        this.unitId = unitId;
        this.unitNumber = unitNumber;
    }
    public Integer getUnitId() {
        return unitId;
    }
    public void setUnitId(Integer unitId) {
        this.unitId = unitId;
    }
    public int getUnitNumber() {
        return unitNumber;
    }
    public void setUnitNumber(int unitNumber) {
        this.unitNumber = unitNumber;
    }
    @XmlTransient
    public List<Lesson> getLessonList() {
        return lessonList;
    }
    public void setLessonList(List<Lesson> lessonList) {
        this.lessonList = lessonList;
    }
    public Course getCourseId() {
        return courseId;
    }
    public void setCourseId(Course courseId) {
        this.courseId = courseId;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (unitId != null ? unitId.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Unit)) {
            return false;
        }
        Unit other = (Unit) object;
        if ((this.unitId == null && other.unitId != null) || (this.unitId != null && !this.unitId.equals(other.unitId))) {
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return "entities.Unit[ unitId=" + unitId + " ]";
    }
}

这是创建课程的jsf页面:

<h:form id="CourseCreateForm" enctype="multipart/form-data">
                <h:panelGroup id="display">
                    <p:panelGrid columns="2" rendered="#{courseController.selected != null}">
                        <p:outputLabel value="#{admin.CreateCourseLabel_sectionId}" for="sectionId" />
                        <h:selectOneMenu id="sectionId" value="#{courseController.selected.sectionId}" required="true" requiredMessage="#{admin.EditCourseRequiredMessage_sectionId}">
                            <f:selectItem itemLabel="Select One" itemValue="" noSelectionOption="true" />
                            <f:selectItems value="#{sectionController.itemsAvailableSelectOne}"
                                           var="sectionIdItem"
                                           itemLabel="#{sectionIdItem.sectionName}"
                                           itemValue="#{sectionIdItem}"/>
                        </h:selectOneMenu>
                        <p:outputLabel value="#{admin.CreateCourseLabel_courseName}" for="courseName" />
                        <p:inputText id="courseName" value="#{courseController.selected.courseName}" title="#{admin.CreateCourseTitle_courseName}" required="true" requiredMessage="#{admin.CreateCourseRequiredMessage_courseName}"/>
                        <p:outputLabel value="#{admin.CreateCourseLabel_courseDesc}" for="courseDesc" />
                        <p:inputText id="courseDesc" value="#{courseController.selected.courseDesc}" title="#{admin.CreateCourseTitle_courseDesc}" required="true" requiredMessage="#{admin.CreateCourseRequiredMessage_courseDesc}"/>
                        <p:outputLabel value="#{admin.CreateCourseLabel_coursehours}" for="coursehours" />
                        <p:inputText id="coursehours" value="#{courseController.selected.coursehours}" title="#{admin.CreateCourseTitle_coursehours}" required="true" requiredMessage="#{admin.CreateCourseRequiredMessage_coursehours}"/>
                        <p:outputLabel value="#{admin.CreateCourseLabel_courseUnits}" for="courseUnits" />
                        <p:inputText id="courseUnits" value="#{courseController.selected.courseUnits}" title="#{admin.CreateCourseTitle_courseUnits}" required="true" requiredMessage="#{admin.CreateCourseRequiredMessage_courseUnits}"/>
                        <p:outputLabel value="#{admin.CreateCourseLabel_coursePoints}" for="coursePoints" />
                        <p:inputText id="coursePoints" value="#{courseController.selected.coursePoints}" title="#{admin.CreateCourseTitle_coursePoints}" required="true" requiredMessage="#{admin.CreateCourseRequiredMessage_coursePoints}"/>
                        <p:outputLabel value="#{admin.CreateCourseLabel_coursePhoto}" for="coursePhoto" />
                        <p:inputText id="coursePhoto" value="#{courseController.selected.coursePhoto}" title="#{admin.CreateCourseTitle_coursePhoto}" required="true" requiredMessage="#{admin.CreateCourseRequiredMessage_coursePhoto}"/>
                        <p:outputLabel value="test" for="coursePhotoa" />
                        <p:fileUpload id="coursePhotoa" auto="true" fileUploadListener="#{photoUploader.upload}" mode="simple" dragDropSupport="false" sizeLimit="100000" fileLimit="1" allowTypes="/(.|/)(gif|jpe?g|png)$/" />
                        <p:outputLabel  value="#{admin.CreateCourseLabel_courseLevel}" for="courseLevel" />
                        <p:inputText id="courseLevel" value="#{courseController.selected.courseLevel}" title="#{admin.CreateCourseTitle_courseLevel}" required="true" requiredMessage="#{admin.CreateCourseRequiredMessage_courseLevel}"/>
                        <p:outputLabel value="#{admin.CreateCourseLabel_courseActive}" for="courseActive" />
                        <p:selectBooleanCheckbox id="courseActive" value="#{courseController.selected.courseActive}" required="true" requiredMessage="#{admin.EditCourseRequiredMessage_courseActive}"/>
                        <p:outputLabel value="#{admin.CreateCourseLabel_achievementId}" for="achievementId" />
                        <h:selectOneMenu id="achievementId" value="#{courseController.selected.achievementId}" >
                            <f:selectItem itemLabel="Select One" itemValue="" noSelectionOption="true" />
                            <f:selectItems value="#{achievementsController.itemsAvailableSelectOne}"
                                           var="achievementIdItem"
                                           itemLabel="#{achievementIdItem.achievementName}"
                                           itemValue="#{achievementIdItem}"/>
                        </h:selectOneMenu>
                        <p:outputLabel value="#{admin.CreateCourseLabel_languageId}" for="languageId" />
                        <h:selectOneMenu id="languageId" value="#{courseController.selected.languageId}" required="true" requiredMessage="#{admin.EditCourseRequiredMessage_languageId}">
                            <f:selectItem itemLabel="Select One" itemValue="" noSelectionOption="true" />
                            <f:selectItems value="#{languageController.itemsAvailableSelectOne}"
                                           var="languageIdItem"
                                           itemLabel="#{languageIdItem.languageName}"
                                           itemValue="#{languageIdItem}"/>
                        </h:selectOneMenu>
                        <p:outputLabel value="#{admin.CreateCourseLabel_quizId}" for="quizId" />
                        <h:selectOneMenu id="quizId" value="#{courseController.selected.quizId}" >
                            <f:selectItem itemLabel="Select One" itemValue="" noSelectionOption="true" />
                            <f:selectItems value="#{quizController.itemsAvailableSelectOne}"
                                           var="quizIdItem"
                                           itemLabel="#{quizIdItem.quizName}"
                                           itemValue="#{quizIdItem}"/>
                        </h:selectOneMenu>
                    </p:panelGrid>
                    <p:commandButton actionListener="#{courseController.create}" value="#{admin.Save}" update="display,:CourseListForm:datalist,:growl" oncomplete="handleSubmit(args,'CourseCreateDialog');">
                        <f:actionListener binding="#{courseController.createUnit}" />
                    </p:commandButton>
                    <p:commandButton value="#{admin.Cancel}" onclick="PF('CourseCreateDialog').hide()"/>
                </h:panelGroup>
            </h:form>

和这个创建方法在课程管理豆:

public void create() {
        persist(PersistAction.CREATE, ResourceBundle.getBundle("/Admin").getString("CourseCreated"));
        if (!JsfUtil.isValidationFailed()) {
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

首先要说明的是:

  1. 您不应该添加带有id的构造函数。带有@GeneratedValue的id是由您的JPA提供程序(即您的数据库)自动设置的,即使没有构造函数也是如此(同样适用于setUnitId
  2. 你不需要@JoinColumn注释,@ManyToOne(optional = false)注释就足够了——只要你把课程称为course(而不是courseId
  3. 您展示的是Unit实现,但谈论的却是Course实体

然而,结果是一样的:

public class Course {
     ...
     @OneToMany(mappedBy = "course", cascade = CascadeType.ALL, orphanRemoval = true)
     private List<Unit> units = new ArrayList<>();
     public int getCourseUnits() {
          return units.size();
     }
     public void setCourseUnits(int numberOfUnits) {
          if (units.size() > numberOfUnits) {
              units.sublist(numberOfUnits, units.size()).clear();
          } else {
              for (int i = units.size(); i < numberOfUnits; i++) {
                  Unit unit = new Unit();
                  unit.setUnitNumber(i);
                  units.add(unit);
              }
          }
     }
}

相关内容

  • 没有找到相关文章

最新更新