gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:38:12 27 4
gpt4 key购买 nike

我刚从 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;
...
}

地址类:

@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)值(?,?,?)

因此出现错误:ERROR: Column 'address_id' cannot be null

我该如何解决这个问题?

.

那些是表格:

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>

最佳答案

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

关于java - hibernate :对象以错误的顺序创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13702990/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com