Hibernate org.hibernate.NonUniqueObjectException

时间:2014-09-29 14:11:05

标签: hibernate orm one-to-one

我正在尝试一对一的单向主键xml映射。当我尝试保存我的Student对象时,我得到NonUniqueObjectException。

学生POJO

public class Student {

    private long studentId;
    private String name;
    private Locker locker;

    public long getStudentId() {
        return studentId;
    }
    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Locker getLocker() {
        return locker;
    }
    public void setLocker(Locker locker) {
        this.locker = locker;
    }
}

Student.hbm.xml

<hibernate-mapping>
    <class name="com.avinash.dto.Student" table="STUDENT">
    <id name="studentId" type="long" column="STUDENT_ID">
        <generator class="foreign">
            <param name="property">locker</param>

        </generator>
    </id>
    <property name="name" type="string">
        <column name="NAME"></column>
    </property>

    <one-to-one name="locker" class="com.pramati.dto.Locker"  constrained="true">

    </one-to-one>

    </class>
</hibernate-mapping>

Locker POJO

public class Locker {

    private long lockerId;
    private String location;

    public long getLockerId() {
        return lockerId;
    }
    public void setLockerId(long lockerId) {
        this.lockerId = lockerId;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
}

Locker.hbm.xml

<hibernate-mapping>
    <class name="com.avinash.dto.Locker" table="LOCKER">
        <id name="lockerId" type="long" column="LOCKER_ID">
            <generator class="sequence"></generator>
        </id>
        <property name="location" type="string">
            <column name="LOCATION"></column>
        </property>
    </class>
</hibernate-mapping>

我的java代码如下

public static void main(String [] args){

    Session session = HibernateUtil.getSessionfactory().openSession();
    session.beginTransaction();

    Locker locker = new Locker();
    locker.setLocation("Hyderabad");

    Student student = new Student();
    student.setName("Avinash");
    student.setLocker(locker);

    Student student1 = new Student();
    student1.setName("Naresh");
    student1.setLocker(locker);

    session.save(student);
    session.save(student1);
    session.getTransaction().commit();
    session.close();
    HibernateUtil.shutdown();
}

我正在创建两个不同的Student对象,并将同一个locker对象分配给同一会话中的两个Student对象。我怀疑是

由于它是一对一的关系,我的期望是它应该抛出ConstraintViolationException,但为什么它会抛出NonUniqueObjectException。我没有重写equals()和hashCode()。

0 个答案:

没有答案