I'm the folloing having a trouble with my application:
I've a @OneToMany relation as show above:
The Bar class:
@Entity
public class Bar {
@Id
private Long id;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
@JoinTable(name = "bar_foo_relation",
joinColumns = { @JoinColumn(name = "id", referencedColumnName = "bar_id") },
inverseJoinColumns = { @JoinColumn(name = "id", referencedColumnName = "foo_id") } )
private List<Foo> fooList;
// Getters & Setters
}
The Foo class:
@Entity
public class Foo {
@Id
private Long id;
private String fooValue;
// Getters & Setters
}
When I create a new instance of Bar, with fooList populated, like this:
{
"id": null,
"fooList": [
{
"id": null,
"fooValue": "foo"
},
{
"id": null,
"fooValue": "foo"
}
]
}
I call manager.persist(bar)
and it works all fine.
DB bar table:
row | id ----+---- 01 | 01
DB bar_foo_relation table:
row |bar_id|foo_id ----+------+------ 01 | 01| 01 01 | 01| 02
DB foo table:
row | id|foovalue ----+----+-------- 01 | 01|foo 02 | 02|foo
But, when I put new Foo instances like this:
{
"id": 1,
"fooList": [
{
"id": 1,
"fooValue": "foo"
},
{
"id": 2,
"fooValue": "foo"
},
// New instance of Foo to persist
{
"id": null,
"fooValue": "foo" // fooValue is setted
},
// New instance of Foo to persist
{
"id": null,
"fooValue": "foo" // fooValue is setted
}
]
}
and call manager.merge(bar)
the new instances of Foo this happen on DB: DB bar table:
row | id ----+---- 01 | 01
DB bar_foo_relation table:
row |bar_id|foo_id ----+------+------ 01 | 01| 01 01 | 01| 02 01 | 01| 03 // New instance of Foo got persisted and is referenced here 01 | 01| 04 // New instance of Foo got persisted and is referenced here
DB foo table:
row | id|foovalue ----+----+-------- 01 | 01|foo 02 | 02|foo 02 | 03|null // New instance of Foo without foovalue 02 | 04|null // New instance of Foo without foovalue
The column fooValeu of the new Foos is setted to null
.
I don't know why it's happening. Can someone clarify me about it?
My environment is: Java 1.7 PostgreSQL 9.3 Hibernate 4.3.6.Final
Try using the following:
cascade={CascadeType.PERSIST, CascadeType.MERGE}
I believe the behavior you're seeing (though i'm not 100% certain) is that when you call merge on non persisted child objects the entity manager knows there are associated objects but because they're not part of the persisted context the default constructor of Foo is called behind the scenes. Telling your parent object to cascade the merge operation OR manually saving the children object would stop this from happening.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.