Person table has optional one to many association. I am trying this strategy as below. In this, foreign key value in address table is inserted as null. Could any body please tell me how to get rid of this?
If there any other soluti
on for optional one to one strategy, please let me know.
public class Person
{
protected int id;
protected int version;
private List<Address> addresses = new ArrayList<Address>();
@Id
@Column(name = "Id", insertable = false, updatable = false)
@GeneratedValue(strat
egy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Version
@Column(name = "Version")
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
@OneToMany(fetch = FetchType.LAZY)
@Cascade( { org.hibernate.annotations.CascadeType.SAVE_UPDATE,
org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
@ForeignKey(name = "FK_ADDRESS")
@Index(name = "IDX_ADDRESS")
@JoinColumn(name = "PersonId", nullable = true, insertable = true, updatable = false)
public List<Address> getAddresses()
{
return addresses;
}
public void setAddresses(List<Address> address)
{
addresses = address;
}
}
public class Address
{
protected int id;
protected int version;
private
String place;
//other properties
@Id
@Column(name = "Id", insertable = false, updatable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Version
@Column(name = "Version")
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
@Column(name = "Place")
public String getPlace()
{
return addresses;
}
public void setPlace(String placeName)
{
place = placeName;
}
}
List<Address> addresses = new ArrayList<Address>();
Address address1 = new Address();
addresss.setPlace("XYZ");
addresses.add(address1);
Person person = new Person();
person.setAddresses(addresses);
HibernateTemplate template = getHibernateTemplate();
template.save(addresses);
When i do this operation, entries are getting creating in both tables. But problem, PersonId which is foreign key column in
address table is having value as null.
I am not getting what is the problem with my domain model. If i declare JoinColumn as nullable as false it is working fine . But my requirement is it can be null and if we provide some address, it should have
personId. Please tell me what is wrong with my domain class?