Hibernate复合键不起作用

时间:2011-01-07 18:55:58

标签: java database hibernate

以下是我正在使用的代码:

数据库:

 CREATE TABLE IF NOT EXISTS `btech_faculty_assigned` (
      `subject_id` varchar(8) NOT NULL,
      `year` varchar(4) NOT NULL,
      `section` varchar(1) NOT NULL,
      `branch` varchar(10) NOT NULL,
      `semister` varchar(1) NOT NULL,
      `FID` varchar(10) NOT NULL,
      `islab` varchar(1) NOT NULL,
      PRIMARY KEY (`subject_id`,`year`,`section`,`branch`,`semister`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

hbm文件:

<?xml version="1.0"?>
<!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.att_marks.students.BtechFacultyAssigned" table="btech_faculty_assigned">
<composite-id>
<key-property name="subjectID" column="subject_id"/>
<key-property name="year" column="year"/>
<key-property name="section" column="section"/>
<key-property name="branch" column="branch"/>
<key-property name="semister" column="semister"/>
</composite-id>

<property name="FID" column="FID"></property>
<property name="islab" column="islab"></property>
</class>
</hibernate-mapping>

POJO档案:

package com.att_marks.students;

public class BtechFacultyAssigned {
    private String subjectID;
    public String getSubjectID() {
        return subjectID;
    }
    public void setSubjectID(String subjectID) {
        this.subjectID = subjectID;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getSeciton() {
        return section;
    }
    public void setSeciton(String section) {
        this.section = section;
    }
    public String getFID() {
        return FID;
    }
    public void setFID(String fID) {
        FID = fID;
    }
    public String getSemister() {
        return semister;
    }
    public void setSemister(String semister) {
        this.semister = semister;
    }
    public String getBranch() {
        return branch;
    }
    public void setBranch(String branch) {
        this.branch = branch;
    }
    public String getIslab() {
        return islab;
    }
    public void setIslab(String islab) {
        this.islab = islab;
    }
    private String year;
    private String section;
    private String FID;
    private String semister;
    private String branch;
    private String islab;

}

只要此hbm文件未包含在配置文件中,整个项目就可以正常工作。当此文件包含在配置文件中时,sessionFactory.createQuery(query)文件将抛出空指针异常。

1 个答案:

答案 0 :(得分:3)

Hibernate doc说:

  

具有复合键的表可以是   用多个属性映射   class作为标识符属性。该     元素接受     财产映射和    作为孩子的映射   元件。

     

持久化类必须覆盖   equals()和hashCode()来实现   复合标识符相等。它必须   也实现了Serializable。

即使这可能不是您问题的原因(但行为如下),您也必须遵循此要求并添加equalshashcodeserilizable