2

我刚刚从 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>
4

1 回答 1

1

您应该在班级字段上指定注释cascade属性以保存上学前的地址。例如,@ManyToOneaddressSchoolCascadeType.ALL

于 2012-12-04T13:17:54.373 回答