I just switched from XML mapping to annotations and had to realize that my serialization class does not work any more!
I hope you can help me to find out the reason 🙂
I have a School class that contains an 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;
...
}
the Address class:
@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
...
}
I try to serialize like this:
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();
This worked before with XML, but now doesn’t..
The first Hibernate query action visible on the console is:
Hibernate: insert into schools (address_id, layout_id, name) values (?, ?, ?)
Therefore an error occurs: ERROR: Column ‘address_id’ cannot be null
How can I fix this?
.
Those are the tables:
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)
);
In my hibernte.cfg.xml I have the following:
<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>
You should specify
cascadeproperty of@ManyToOneannotation onaddressfield ofSchoolclass to save address before school. For example,CascadeType.ALL