简体   繁体   English

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

[英]how to generate data automatically into database table has relation with another table using JSF 2.2 AND JPA

I work on JSF 2.2 AND JPA 2.1 我致力于JSF 2.2和JPA 2.1

I have two tables course and units these table has relation (each course can have many units) 我有两个表的课程和这些表有关系的单位(每个课程可以有很多单位)

course table has field to set number of units 课程表中有设置单位数量的字段

I want to generate units automatically when I create course using number of unit. 我想使用单位数创建课程时自动生成单位。

I try to do this but I don't success until now 我尝试这样做,但直到现在我都没有成功

unit entity class: 单位实体类:

@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 + " ]";
    }

}

this is jsf page of create course: 这是创建课程的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>

and this create method in course manged bean: 这个创建方法当然是在管理过的bean中:

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

First some remarks: 首先说一下:

  1. You should not add a constructor with an id. 您不应添加带有ID的构造函数。 An ID with @GeneratedValue is set by your JPA provider (resp. your database) automatically, even without the constructor (same applies to setUnitId ). 即使没有构造函数,JPA提供程序(也就是数据库)都会自动设置带有@GeneratedValue的ID,即使没有构造函数(对setUnitId同样适用)。
  2. You don't need the @JoinColumn annotation, the @ManyToOne(optional = false) annotation is already enough - as long as you call the Course a course (not a courseId ). 您不需要@JoinColumn批注, @ManyToOne(optional = false)批注就足够了-只要您将Course称为course (不是courseId )。
  3. You are showing the Unit implementation but talking of the Course entity. 您正在显示Unit实现,但是正在谈论Course实体。

Nevertheless the result is the same: 但是结果是一样的:

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);
              }
          }
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 spring jpa 自动创建关系/表? - How to get spring jpa to create relation/table automatically? 如何使用 JPA 锁定数据库行,直到更新另一个表 - How to lock a database row using JPA until another table is updated 如何从JPA实体和另一个实体检索JavaFX表的数据? - How to retrieve data for a JavaFX table from a JPA entity in relation with another one? 使用Java Play 2框架和Spring Data JPA自动生成数据库表 - Auto generate a database table with java play 2 framework and spring data jpa 如何在Spring Boot中使用hibernate / jpa在mysql关系表中插入数据 - How to insert the data in mysql relation table using hibernate/jpa in Spring Boot 从具有Spring和JPA批注的两个表之间具有外键关系的html表单(使用Thymeleaf)保存数据的问题 - Problem with saving data from a html form (using Thymeleaf) that has a foreign key relation between two table with Spring and JPA annotations 如何在JSF页面中显示包含数据库数据的数据表 - How to display data table in JSF page with database data 如何使用JDBC在MS-Access中将数据插入到具有PK,FK关系的两个表中 - How to insert data into two table which has PK , FK relation in MS-Access using JDBC 如何将数据从一张表导入另一张表 - SpringBoot JPA /MySQL - How to import data from one table to another - SpringBoot JPA /MySQL 我在尝试使用 JPA 在 spring 引导中自动生成数据库中的表时遇到问题 - I had a problem while trying to genrate automatically the table in the database in spring boot using JPA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM