I'm using JPA2 with EclipseLink implementation
![Simple table structure][1]
Here are the two tables which I try to map and the JPA annotations.
public class Story implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
Integer id;
@Temporal(TemporalType.TIMESTAMP)
@Column (name="DATE_CREATED")
Date dateCreated;
String title;
String description;
@Column(name="AUTHOR_ID")
Integer authorId;
@Column(name="COUNTRY_ID")
Integer countryId;
private String reviews;
@OneToMany(mappedBy = "story", cascade=CascadeType.ALL)
private List<Tip> tipList;
}
public class Tip implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private String description;
private Integer vote;
@ManyToOne (cascade=CascadeType.ALL)
@JoinColumn(name="STORY_ID", referencedColumnName="ID")
private Story story;
}
As a simple example I would like to persist a story and some story related tips in the same transaction. Here is the section of code which does that:
Story newStory = new Story(title, body, ...);
EntityTransaction transaction = em.getTransaction().begin();
boolean completed = storyService.create(newStory);
//The tips are saved as a List<String>. This methods creates the needed List<Tip> from the Strings
List<Tip> tips = TipUtil.getTipList(tipList);
newStory.setTipList(tips)
transaction.commit();
I have no errors and all the entities are persisted in the database. The problem is that in the tip table the story_id
field is always NULL
. I can imagine that JPA is unable to get the new id
from the story table. What's the correct approach here?
LE
In the current state of the code, the Tip
entities are persisted but the country ID remains null.