2

I have the following classes:

@Entity
@Table(name = "PARENT")
public class Parent {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PARENT_ID", unique = true, nullable = false, insertable = true, updatable = true)
private Long parentId;


@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER ) 
@JoinColumn(name="PARENT_ID", nullable = false)
private List<Child> children;


public Parent(List<Child> children) {
this.children = children;
}


..
... Getters\Setters

}


@Entity
@Table(name = "CHILD")
public class Child {

@Id 
@Column(name = "TYPE", unique = false, nullable = false)
private String type;

@Column(name = "RANK", unique = false, nullable = false, insertable = true, updatable = false)
private String rank;

}

The 'PARENT_ID' is foreign key in "CHILD" table. so it makes "CHILD" table having 2 columns forming its PRIMARY_KEY.

I perform the following insert:

List<Child> children = new LinkedList<Child>();
children.add(new Child("1,2,3,4"));
children.add(new Child("1,2,3,4"));

Parent parent = new Parent(children);

session.save(parent);

If both tables are empty it creates the 'parent' and 'children' correctly by assigning PARENT_ID!, BUT if 'Child' entries are already exist in table it performs update instead of insert!

PAY ATTENTION that both 'child' have the same "TYPE" ("1,2,3,4"), but they should have different "PARENT_ID" though.

What am I missing here ????

Thank you !

Shvalb
  • 1,835
  • 2
  • 30
  • 60

1 Answers1

0

In your child you need to have an instance of the parent and i believe you have misplaced the JoinColumn in your Parent class which should be in your child class. And the constructor is not required in your Parent class.

Parent Class should look something like:

@Entity
@Table(name = "PARENT")
public class Parent {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PARENT_ID", unique = true, nullable = false, insertable = true,          updatable = true)
private Long parentId;


@Embedded
private Child children;


..
... Getters\Setters (MAke sure you have the getter setter for children as well)

}

Your Child class should be something like:

@Embeddable
@Table(name = "CHILD")
public class Child {

@Id 
@Column(name = "TYPE", unique = false, nullable = false)
private String type;

@Column(name = "RANK", unique = false, nullable = false, insertable = true, updatable = false)
private String rank;


    //getter and setters
amitsalyan
  • 658
  • 1
  • 8
  • 29
  • yeah, that might work, but now it a bidirectional association which is nice but adds unneeded complexity to code. – Shvalb Jul 08 '13 at 07:23
  • Yes, you may be right, Embedded and Embeddable could be better approach. However the context where you would be using this will be more important – amitsalyan Jul 10 '13 at 01:21