Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Foreign key value null if nullable true in @OneToMany assoc

 
kemparaju kn
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 solution 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(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;
}


@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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic