@ManyToOne映射无法保存父 ID
2022-09-03 14:10:19
我正在使用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;
}
作为一个简单的例子,我想在同一笔交易中保留一个故事和一些与故事相关的提示。下面是执行此操作的代码部分:
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();
我没有错误,所有实体都保留在数据库中。问题是,在提示表中,字段始终为 。我可以想象JPA无法从故事表中获取新的内容。这里的正确方法是什么?story_id
NULL
id
乐
在代码的当前状态下,实体将持久化,但国家/地区 ID 仍为 null。Tip