hibernate:以错误的顺序创建的对象?

时间:2012-12-04 12:32:45

标签: java hibernate

我刚刚从XML映射切换到注释,并且必须意识到我的序列化类不再起作用了! 我希望你能帮助我找出原因:)

我有一个School类,其中包含Address

@Entity
@Table(name="schools")
    public class School {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @ManyToOne
    @JoinColumn(name="address_id", nullable=true)
    private Address address;
        ...
}

Address班级:

@Entity
@Table(name="addresses")
public class Address {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name="street", nullable=false, updatable=true)
    private String street;      // with nr
    ...
}

我尝试像这样序列化:

sessionFactory = MyFactory.getSessionFactory();
            session = sessionFactory.openSession();

            Transaction tx = session.beginTransaction();

            School mbs = new School("interesting school");
            Address a = new Address("garden street 5","12345", "somewhere");
            mbs.setAddress(a);

            session.save(mbs);
            tx.commit();

之前使用XML,但现在没有..

控制台上可见的第一个Hibernate查询操作是: Hibernate:插入学校(address_id,layout_id,name)值(?,?,?)

因此发生错误:错误:列'address_id'不能为空

我该如何解决这个问题?

这些是表格:

CREATE TABLE schools(
    id INTEGER NOT NULL AUTO_INCREMENT,
    name CHAR(50),

    address_id INTEGER NOT NULL,
    layout_id INTEGER NOT NULL,

    CONSTRAINT fk_address FOREIGN KEY (address_id) REFERENCES addresses(id),
    CONSTRAINT fk_layout FOREIGN KEY (layout_id) REFERENCES layout_headers(id),

    PRIMARY KEY (id)
);
CREATE TABLE addresses(
    id INTEGER NOT NULL AUTO_INCREMENT,
    street CHAR(55),
    zip CHAR(6),
    city CHAR(60),

    CONSTRAINT addr_pk PRIMARY KEY (id)
);

在我的hibernte.cfg.xml中,我有以下内容:

<hibernate-configuration>
    <session-factory>
     ...
        <mapping class="creator.models.school.Address" />
        <mapping class="creator.models.school.Report" />
        <mapping class="creator.models.school.School" />
        <mapping class="creator.models.school.SchoolClass" />
        ...
    </session-factory>
</hibernate-configuration>

1 个答案:

答案 0 :(得分:1)

您应在cascade课程的@ManyToOne字段指定address注释的School属性,以便在上学前保存地址。例如,CascadeType.ALL