I am working on a web app and I am using JSF and JPA(EclipseLink). I have the tables story and story_translate, which are mapped as follows:
@Entity
@Table(name = "story")
public class Story{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private String title;
private String description;
@OneToMany(mappedBy = "story", cascade=CascadeType.ALL)
private List<StoryTranslate> translateList;
//getters and setters
}
@Entity
@Table(name = "story_translate")
public class StoryTranslate{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
@Column(name="STORY_ID")
private Integer storyId;
@ManyToOne
@JoinColumn(name="story_id", referencedColumnName="id", updatable=false, insertable=false)
private Story story;
//some other fields, getters and setters
}
In a ManagedBean I am doing the following:
StoryTranslate translate = new StoryTranslate(null, sessionController.getEntity().getId(), getAuthUser().getId(), language,
title, description, new Date(), false);
EntityTransaction transaction = TransactionSingleton.getActiveInstance();
Story story = storyService.read(sessionController.getEntity().getId());
if (story != null){
if (story.getTranslateList() == null){
story.setTranslateList(new ArrayList<StoryTranslate>());
}
story.getTranslateList().add(translate);
translate.setStory(story);
}
transaction.commit();
When I try to create a new StoryTranslate, I get a DatabaseException, saying the story_id cannot be null.
I have managed relationships before, but I have never seen this error.
Where is the problem?
EDIT: I am sorry, but I have forgotten about another part of the mapping(must be the lack of sleep).
The problem is that your declare the
storyIdproperty in theStoryTranslateclass for theSTORY_IDcolumn but when adding a newStoryTranslate, you do not set any value to itsstoryIdproperty and I believeSTORY_IDcolumn has a NOT NULL constraint and that why you get the exception saying that story_id cannot be null.The problem should be fixed once you set the
storyIdproperty of theStoryTranslateinstance before committing the transaction .But it is strange that you map the
STORY_IDcolumn to two different properties (storyIdandstory) of theStoryTranslateclass . Actually you do not need to declarestoryIdproperty as this value can be retrieved from thestoryinstance . I suggest you change the mapping ofStoryTranslateto the following and your code should work fine without any changes.