problem in persisting the object in oneToMany and manyToOne relationship in hibernate
I have one doubt which is related to hibernate ... if I have following scenerio
@Entity
@Table(name="CONTINENT")
public class Continent {
@Id
@GeneratedValue
private Integer id;
private String name;
@OneToMany(cascade = {CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinColumn(name = "CONTI_ID")
private Set<Country> countries;
public Continent() {
}
Following is my Country class
@Entity
@Table(name="COUNTRY")
public class Country {
@Id
@GeneratedValue
//@Column(name="CTRY_ID")
private Integer id;
@Column(name="CTRY_NAME")
private String name;
private int area;
@ManyToOne
@JoinColumn(name = "CONTI_ID")
private Continent continent;
@Enumerated(EnumType.STRING)
private LanguageSpoken lang;
}
I am trying to perform following
updateCountry(){
Continent c1 = new Continent();
Country c = getNewCountry(c1);
c.setArea("berlin");
continentDao.update(c1);// **will child's locat开发者_开发知识库ion be set in db????**
c.getId().equals(1);//**If above questions answer is yes then why it throws null pointer exception**
}
getNewCountry(c1){
Country c = new Country();
c.setName("germany");
c1.getCountry().add(c);
continentDao.update(c1);
}
Can some one please help me in understanding the questions in comments why I am getting Null Pointer at this line c.getId()
In any bi-directional relationship you should chose one side to be the owning side. This is done by setting the "mappedBy" attribute. Generally that would be done on the one-to-many side (Continent in your case). With that mapping correct you will avoid any contention between the country and the continent when saving.
The second part of the problem is exactly what rationalSpring mentioned. Modifying one side of a bi-directional relationship and saving it will update the record in the database, but it will not update any object graphs you already have loaded. For this reason it's usually best to have a service method that takes care of managing the object graph. In your case, it would take care of making sure the bi-directional link between country and continent are set correctly, then you would save the owning side of the relationship.
In a bidirectional relationship, you have to wire both sides of the relationship. Here, you have wired only one side
c1.getCountry().add(c);
You also need to wire the reverse relationship, i.e.
c.setContinent(c1);
Additionally, c.getId() might be null because you have set it to a GeneratedValue and it hasn't been persisted yet. So wire both sides of the relationship.
精彩评论