Hibernate version:
3.2 GA
Annotations 3.2 GA
Name and version of the database you are using:
Postgres 8.1
I cannot get hibernate to work with the collection I want to setup. Basically the problem is that the @OneToMany is (instead of deleting records from the many side of the relationship) trying to update the not null foriegn keys and falling over. I cannot figure out how to get it working.
Basically the scenario is this. I want to be able to add an object to a collection in another class, hit save, and get it persisted correctly.
Here's some stripped down code:
Code:
@Entity
@Table(name = "customer")
@SequenceGenerator(name = "SEQ_CUSTOMER_ID"
, sequenceName = "seq_customer_id", allocationSize = 10)
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE
, generator = "SEQ_CUSTOMER_ID")
@Column(name = "customer_id")
private Integer id;
@OneToMany(cascade = {CascadeType.ALL })
@OrderBy("name")
@JoinColumn(name = "customer_id")
private List<Project> projects;
public void addProject(Project project) {
if (this.projects == null) {
this.projects = new ArrayList<Project>();
}
this.projects.add(project);
}
....
}
@Entity
@Table(name = "project")
@SequenceGenerator(name = "SEQ_PROJECT_ID", sequenceName = "seq_project_id"
, allocationSize = 10)
public class Project {
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE, generator = "SEQ_PROJECT_ID")
@Column(name = "project_id")
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "customer_id", nullable = false
, updatable = false)
@ForeignKey(name = "fk_project_customer")
@Index(name = "idx_project_customer_id")
private Customer customer;
....
}
And the basic test I am running:
Code:
@Test
public void addProject() {
Customer customer = this.createNewCustomer("test");
Project project = new Project();
project.setCustomer(customer);
customer.addProject(project);
this.sessionFactory.getCurrentSession().saveOrUpdate(customer);
}
The generated SQL (show_sql=true):Code:
Hibernate:
select
nextval ('seq_customer_id')
Hibernate:
insert
into
customer
(created, name, customer_id)
values
(?, ?, ?)
Hibernate:
select
nextval ('seq_project_id')
Hibernate:
insert
into
project
(created, customer_id, name, priority, project_id)
values
(?, ?, ?, ?, ?)
Hibernate:
update
customer
set
created=?,
name=?
where
customer_id=?
Hibernate:
update
project
set
customer_id=null
where
customer_id=?
As you can see hibernate is trying to null out the foreign key. If I allow the foreign key to be null, it then follows up with an update to update the customer id.
All of this seems silly. In this case there should not be any updates at all The customer has been created and returned before the collection is amended with a new project. So a simple insert is all that should be necessary. I'm pretty sure that this sort of relationship works fine with hbm files. But I cannot get it working from annotations.
Any help appreciated.
Derek