简体   繁体   中英

How to create a Hibernate mapping file for a oneToMany relationship with composite primary and foreign key as well?

The database table are:

Create table CatalogRequirements (
    semester varchar(20) NOT NULL,
    year int NOT NULL,
    program varchar(20) not null,
    GPA decimal(5 , 2 ) NOT NULL,
    ILETS decimal(5 , 2 ),
    TOFEL int,
    Backlogs int,
    Pre_requisite1 varchar(20),
    Pre_requisite2 varchar(20),
    compsmingpa decimal(5,2) not null,
    compsminHours int not null,
    Primary key (semester , year,program)
);
    Create table Catalog_Course (
    courseNum int NOT NULL,
    semester varchar(20) not null,
    year int not  null,
    program varchar(20) not null,
    Hours int NOT NULL,
    MIN_GPA decimal(3 , 2 ) NOT NULL,primary key(coursenum,semester,year,program),
    FOREIGN KEY (coursenum)
        references nwcourse (coursenum),
    FOREIGN KEY (semester,year,program)
        references CatalogRequirements (semester,year,program)
);

The managedbean files are

/* This is CatalogRequirement Class */

 @ManagedBean
 @SessionScoped
 @Entity
 @IdClass(CatalogRequirementsId.class)
 public class CatalogRequirements implements Serializable{


   @Id
   private String semester;
   @Id
   private int year;
   @Id
   private String program;
   @Id
   CatalogRequirementsId crPK = new CatalogRequirementsId();
   private double GRE;
private double IELTS;
private int TOEFL;
private int Backlogs;
private String PreRequisites1;
private String PreRequisites2;
private double compsMinGpa;
private int CompsMinHours;
private CatalogCourse cc;


@OneToMany(mappedBy = "catalogrequirements")
private Set<CatalogCourse> catalogCourses;

public CatalogRequirements() {
}

public CatalogRequirements(double GRE,double IELTS, int TOEFL, int Backlogs, String PreRequisites1, String PreRequisites2, double compsMinGpa, int CompsMinHours) {
    this.GRE = GRE;
    this.IELTS = IELTS;
    this.TOEFL = TOEFL;
    this.Backlogs = Backlogs;
    this.PreRequisites1 = PreRequisites1;
    this.PreRequisites2 = PreRequisites2;
    this.compsMinGpa = compsMinGpa;
    this.CompsMinHours = CompsMinHours;
}

public CatalogRequirementsId getCrPK() {
    return crPK;
}

public void setCrPK(CatalogRequirementsId crPK) {
    this.crPK = crPK;
}

public Set<CatalogCourse> getCatalogCourses() {
    return catalogCourses;
}

public void setCatalogCourses(Set<CatalogCourse> catalogCourses) {
    this.catalogCourses = catalogCourses;
}

public double getGRE() {
    return GRE;
}

public void setGRE(double GRE) {
    this.GRE = GRE;
}

public double getIELTS() {
    return IELTS;
}

public void setIELTS(double IELTS) {
    this.IELTS = IELTS;
}

public int getTOEFL() {
    return TOEFL;
}

public void setTOEFL(int TOEFL) {
    this.TOEFL = TOEFL;
}

public int getBacklogs() {
    return Backlogs;
}

public void setBacklogs(int Backlogs) {
    this.Backlogs = Backlogs;
}

public String getPreRequisites1() {
    return PreRequisites1;
}

public void setPreRequisites1(String PreRequisites1) {
    this.PreRequisites1 = PreRequisites1;
}

public String getPreRequisites2() {
    return PreRequisites2;
}

public void setPreRequisites2(String PreRequisites2) {
    this.PreRequisites2 = PreRequisites2;
}

public double getCompsMinGpa() {
    return compsMinGpa;
}

public void setCompsMinGpa(double compsMinGpa) {
    this.compsMinGpa = compsMinGpa;
}

public int getCompsMinHours() {
    return CompsMinHours;
}

public void setCompsMinHours(int CompsMinHours) {
    this.CompsMinHours = CompsMinHours;
}

public String getSemester() {
    return semester;
}

public void setSemester(String semester) {
    this.semester = semester;
}

public int getYear() {
    return year;
}

public void setYear(int year) {
    this.year = year;
}

public String getProgram() {
    return program;
}

public void setProgram(String program) {
    this.program = program;
}

public void saveCatalog() {
    CreateCatalogDao dao = new CreateCatalogDao();
    dao.createCatalog(this);

}
}

This is CatalogRequirementsId Class

 public class CatalogRequirementsId implements Serializable{

private String semester;
private int year;
private String program;

public CatalogRequirementsId() {
}

public CatalogRequirementsId(String semester, int year, String program) {
    this.semester = semester;
    this.year = year;
    this.program = program;
}

public String getSemester() {
    return semester;
}

public void setSemester(String semester) {
    this.semester = semester;
}

public int getYear() {
    return year;
}

public void setYear(int year) {
    this.year = year;
}

public String getProgram() {
    return program;
}

public void setProgram(String program) {
    this.program = program;
}

@Override
public int hashCode() {
    int hash = 7;
    hash = 17 * hash + Objects.hashCode(this.semester);
    hash = 17 * hash + Objects.hashCode(this.year);
    hash = 17 * hash + Objects.hashCode(this.program);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final CatalogRequirementsId other = (CatalogRequirementsId) obj;
    if (!Objects.equals(this.semester, other.semester)) {
        return false;
    }
    if (!Objects.equals(this.year, other.year)) {
        return false;
    }
    if (!Objects.equals(this.program, other.program)) {
        return false;
    }
    return true;
}
}

This is CatalogCourse Class

@ManagedBean
@SessionScoped
@Entity
@IdClass(CatalogCourseId.class)
public class CatalogCourse implements Serializable{

@Id
CatalogCourseId ccid = new CatalogCourseId();
@Id
private String CourseNo;
private int CreditHours;
private double MinGrade;

@ManyToOne
private CatalogRequirements catalogrequirements;
//private CatalogCourse cc;

public CatalogCourse() {
}

public CatalogCourse(String CourseNo, int CreditHours, double MinGrade, CatalogRequirements catalogrequirements) {
    this.CourseNo = CourseNo;
    this.CreditHours = CreditHours;
    this.MinGrade = MinGrade;
    this.catalogrequirements = catalogrequirements;
}

public CatalogRequirements getCatalogrequirements() {
    return catalogrequirements;
}

public void setCatalogrequirements(CatalogRequirements catalogrequirements) {
    this.catalogrequirements = catalogrequirements;
}

public CatalogCourseId getCcid() {
    return ccid;
}

public void setCcid(CatalogCourseId ccid) {
    this.ccid = ccid;
}

public int getCreditHours() {
    return CreditHours;
}

public void setCreditHours(int CreditHours) {
    this.CreditHours = CreditHours;
}

public double getMinGrade() {
    return MinGrade;
}

public void setMinGrade(double MinGrade) {
    this.MinGrade = MinGrade;
}

public String getCourseNo(){
    return getCcid().getCourseNo();
}

public void setCourseNo(String CourseNo){
    getCcid().setCourseNo(CourseNo);
}

public CatalogRequirements getCrFK(){
    return getCcid().getCrFK();
}

public void setCrFK(CatalogRequirements fk){
    getCcid().setCrFK(fk);
}
}

This is CatalogCourseId Class

public class CatalogCourseId implements Serializable {

private String CourseNo;

@ManyToOne
CatalogRequirements crFK;

public String getCourseNo() {
    return CourseNo;
}

public void setCourseNo(String CourseNo) {
    this.CourseNo = CourseNo;
}

public CatalogRequirements getCrFK() {
    return crFK;
}

public void setCrFK(CatalogRequirements crFK) {
    this.crFK = crFK;
}

@Override
public int hashCode() {
    int hash = 7;
    hash = 37 * hash + Objects.hashCode(this.CourseNo);
    hash = 37 * hash + Objects.hashCode(this.crFK);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final CatalogCourseId other = (CatalogCourseId) obj;
    if (!Objects.equals(this.CourseNo, other.CourseNo)) {
        return false;
    }
    if (!Objects.equals(this.crFK, other.crFK)) {
        return false;
    }
    return true;
}
}

The hibernate mapping files are

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD     3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.javaknowledge.entity">
<class name="com.javaknowledge.entity.CatalogRequirements"       table="CatalogRequirements">
    <composite-id class="com.javaknowledge.entity.CatalogRequirementsId" mapped="true">
        <key-property name="semester" column="semester" ></key-property>
        <key-property name="year" column="year" ></key-property>
        <key-property name="program" column="program" ></key-property>
    </composite-id>
    <property name="GRE" column="GPA" />
    <property name="IELTS" column="ILETS" />
    <property name="TOEFL" column="TOFEL" />
    <property name="Backlogs" column="Backlogs" />
    <property name="PreRequisites1" column="Pre_requisite1" />
    <property name="PreRequisites2" column="Pre_requisite2" />
    <property name="compsMinGpa" column="compsmingpa" />
    <property name="compsMinHours" column="compsminHours" />
    <set name="catalogCourses" inverse="true" cascade="all">
        <key not-null="true">
            <column name="semester" ></column>
            <column name="year" ></column>
            <column name="program" ></column>
        </key>
        <one-to-many class="com.javaknowledge.entity.CatalogCourse"></one-to-many>
    </set>

</class>
</hibernate-mapping>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="com.javaknowledge.entity.CatalogCourse" table="Catalog_Course">
     <id name="CourseNo" column="courseNum" type="string" ></id>
    <property name="CreditHours" column="Hours" />
    <property name="MinGrade" column="MIN_GPA" />
    <many-to-one name="catalogrequirements" class="com.javaknowledge.entity.CatalogRequirements" not-null="true">
            <column name="semester" />
            <column name="year" />
            <column name="program" />
    </many-to-one>
</class>
</hibernate-mapping>

The Hibernate configuration file

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate   Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-  configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
   <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/gdp</property>
<property name="hibernate.connection.username">root</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="com/javaknowledge/entity/CatalogRequirements.hbm.xml" />
<mapping resource="com/javaknowledge/entity/CatalogCourse.hbm.xml"/>
 </session-factory>
 </hibernate-configuration>

Finally Dao file to save records to the database

public class CreateCatalogDao {

private CatalogCourse cc;
public void createCatalog(CatalogRequirements cust) {
    Transaction trns = null;
    Session session = HibernateUtil.createSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        session.save(cust);            
        trns.commit();

    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
    } finally {
        session.flush();
        session.close();
    }
}
}

The records are storing into the CatalogRequirements table properly but not in the Catalog_Course . I guess the problem is with hbm files. And also can you explain me how I can retrieve values from catalog_Course table.

To start: Neither of your Entity classes should contain references to their corresponding Id classes (ie CatalogRequirements should not reference CatalogRequirementsId and CatalogCourse should not reference CatalogCourseId ). Never mind that those references should not be annotated as @Id s. :-)

Then you need to use a derived identity. The CatalogCourse classes should look like this:

public class CatalogCourseId implements Serializable {
    private CatalogRequirementsId catalogRequirements;
    private String CourseNo;
    ...
}

@Entity
@IdClass(CatalogCourseId.class)
@Table(name="Catalog_Course")
public class CatalogCourse {
    @Id
    @ManyToOne
    @JoinColumns({
        @JoinColumn(name="semester", referencedColumnName="semester"),
        @JoinColumn(name="year", referencedColumnName="year"),
        @JoinColumn(name="program", referencedColumnName="program")
    })
    private CatalogRequirements catalogRequirements;

    @Id
    @Column(name="courseNum")
    private String courseNo;

    ...
}

Note the attribute name in the IdClass matches the attribute name in the Entity (ie catalogRequirements ), but the attributes' types are different. In the IdClass the attribute type must match the referenced Entity 's IdClass (ie CatalogRequirementsId ).

Derived identities are discussed in the JPA 2.1 spec, section 2.4.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM