Ion*_*nut 13 java entity-relationship jpa
我正在使用JPA2和EclipseLink实现
![简单的桌面结构] [1]
以下是我尝试映射的两个表和JPA注释.
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;
}
Run Code Online (Sandbox Code Playgroud)
作为一个简单的例子,我想在同一个交易中坚持一个故事和一些故事相关的提示.以下是执行此操作的代码部分:
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();
Run Code Online (Sandbox Code Playgroud)
我没有错误,所有实体都保存在数据库中.问题是,在提示表中,story_id字段始终是NULL.我可以想象JPA无法id从故事表中获取新内容.这里的正确方法是什么?
LE
在代码的当前状态中,Tip实体是持久的,但国家ID保持为空.
Pra*_* M 9
对于JPA,始终建议以双向关系更新两侧的关系.这是为了确保数据在应用程序层中保持一致,而与数据库无关.
但是,必须以双向关系更新关系的拥有方.
所以,设置/不设置
story.setTipList(tips)
Run Code Online (Sandbox Code Playgroud)
你决定.但是,如果您希望更改在DB中正确反映,那么您就可以调用
tip.setStory(story)
Run Code Online (Sandbox Code Playgroud)
因为Tip是拥有方在这里,按你的代码.你的代码看起来也不完整.原因是,
storyService.create(newStory)是管理但不是newStory.所以只是设置newStory.setTipList(tips)不会更新数据库因为您需要更新每个孩子的父链接故事.
它的完成方式是在Story类中创建一个addTip(Tip tip)方法.
这种方法可以:
tip.setStory(this);
tipList.add(tip);
Run Code Online (Sandbox Code Playgroud)
如果您不需要双向方法,则可以删除提示中的故事字段,它将解决您的问题
| 归档时间: |
|
| 查看次数: |
4334 次 |
| 最近记录: |