I have a parent table, and I am trying to create a @OneToMany relationship between the parent and child tables (e.g. one parent table can be associated with several child tables).
Parent.java
@Entity
@Table(name = "parent")
public class Threat {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long parentId;
@Column(name = "name")
private String parentName;
}
Child.java
@Entity
@Table(name = "child")
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long childId;
@Column(name = "parent_id")
private long parentId;
@Column(name = "name")
private String childName;
@Column(name = "age")
private Integer childAge;
}
I am having trouble figuring out how to do this given the fact I need to join the primary key of the parent table (parent.id) to a column in the child table that is not the primary key (child.parent_id). Ideally, when I return a Parent object, I would like both the parent id and the list of children displayed, so the parent id is listed in both the parent and children. That way, if the parent has no children, I still have the parent id in my object.
I have been doing some research, and I'm wondering if I should be using
@PrimaryKeyJoinColumn
and/or
@Inheritance(strategy = InheritanceType.JOINED)
I haven't been able to figure out how to implement them though. Any help would be greatly appreciated.
CodePudding user response:
Checkout @JoinColumn. From Java doc :
Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.
Example:
@ManyToOne
@JoinColumn(name="ADDR_ID")
public Address getAddress() { return address; }
Example: unidirectional one-to-many association using a foreign key mapping
// In Customer class
@OneToMany
@JoinColumn(name="CUST_ID") // join column is in table for Order
public Set<Order> getOrders() {return orders;}
With this your entity should look like the following :
@Entity
@Table(name = "parent")
public class Threat {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long parentId;
@Column(name = "name")
private String parentName;
@OneToMany
@JoinColumn(name="parent_id")
private List<Child> children = new ArrayList<>();
}
Now whenever you fetch Parent , you can access the associated child entities.
Additionally you can specify @OneToMany(fetch = FetchType.EAGER)
if you always need child entities fetched whenever you query for parent.