简体   繁体   English

休眠:与分离实体的持续错误

[英]hibernate: persist error with detached entity

I have a problem that I don't understand. 我有一个我不明白的问题。 I have a few entities: 我有几个实体:

Scenario entity 场景实体

@Entity
@Table(name = "scenario")
public class Scenario {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "scenario_id")
private int id;

@Column(name = "title", nullable = false)
private String title;

@NotNull
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Column(name = "creation_date", nullable = false)
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate creationDate;

@OneToMany(mappedBy = "scenario")
@LazyCollection(LazyCollectionOption.FALSE)
private Set<Section> sectionList = new HashSet<Section>();

@ManyToOne
@LazyCollection(LazyCollectionOption.FALSE)
@JoinColumn(name = "id", nullable = false)
private User user;

@OneToMany(mappedBy = "scenario", orphanRemoval=true)
@LazyCollection(LazyCollectionOption.FALSE)
private Set<Plot> plotList = new HashSet<Plot>();

Plot Entity 绘图实体

@Entity
@Table(name = "Plot")
public class Plot {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "plot_id")
private int id;

@Column(name = "name", nullable = false)
private String name;

@Column(name = "description")
private String description;

@ManyToOne
@LazyCollection(LazyCollectionOption.FALSE)
@JoinColumn(name = "id", nullable = false)
private Scenario scenario;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "plot_role", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = {
        @JoinColumn(name = "plot_id") })
private Set<Role> roles = new HashSet<Role>();

And the controller 和控制器

@Autowired
UserService userService;

@Autowired
ScenarioService scenarioService;

@Autowired
PlotService plotService;

@RequestMapping(value = { "/scenario-{id}-newPlot" }, method = RequestMethod.GET)
public String newPlot(ModelMap model, @PathVariable int id) {
    Plot plot = new Plot();
    Scenario scenario = scenarioService.findById(id);
    model.addAttribute("scenario", scenario);
    model.addAttribute("plot", plot);
    model.addAttribute("edit", false);
    return "plotform";
}

@RequestMapping(value = { "/scenario-{id}-newPlot" }, method = RequestMethod.POST)
public String savePlot(@Valid Plot plot, BindingResult result, ModelMap model, @PathVariable int id) {

    if (result.hasErrors()) {
        System.out.println(result.toString());
        return "plotform";
    }
    model.addAttribute("success",
            "Plot " + plot.getName() + " created successfully");
    plot.setScenario(scenarioService.findById(id));
    System.out.println("Plot " + plot.toString());
    plotService.savePlot(plot);

    return "success";
}

I also have, sevices, daos and forms. 我也有服务,手段和形式。 The problem is that when I try to save plot from the form I get: Request processing failed; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.btw.spindle.model.Plot 问题是,当我尝试从表单中保存plot时,我得到: Request processing failed; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.btw.spindle.model.Plot Request processing failed; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.btw.spindle.model.Plot

I dont get how is it detached and how to fix it. 我不明白它是如何分离的以及如何修复它。 I tired adding System.out to check if the neccesary data is being correctly pulled from the form. 我累了添加System.out来检查是否从表单中正确提取了必要数据。 And also I have the user entity (which I did not add here). 而且我还有用户实体(在此未添加)。 The relation between user and scenario is the same (one to many) as between scenario and plot . 之间的关系userscenario是一样的(一对多)的之间的scenarioplot Creation of scenario works perfectly and creation of plots throws this persist exception. scenario创建可以完美地进行,并且plots创建会抛出此持久异常。

Any hints ? 有什么提示吗?

There are multiple reasons that could cause this exception. 导致此异常的原因有多种。 The basic idea behind this exception is that the object which you are trying to persist is not in the persistant state. 此异常背后的基本思想是,您要持久存储的对象未处于持久状态。

Can you check if the Plot object has alreay the ID before you save or persist it? 您可以在保存或保留ID之前检查Plot对象是否已占用ID吗?

EDIT 编辑

You solved, perfect. 您解决了,完美。

Ok MeewU was right. Ok MeewU是正确的。 The problem was because the object had a set up id before being persisted. 问题在于,对象在保留之前具有设置的ID。 The reason for that was: 原因是:

@RequestMapping(value = { "/scenario-{id}-newPlot" }, method = RequestMethod.GET)
public String newPlot(ModelMap model, @PathVariable int id) {

I used it to pass the scenarios ID to add ot in next step to the plot. 我使用它来传递场景ID,以在下一步将ot添加到绘图中。 But it turnes out that the id of scenario was automaticly set as plots id. 但事实证明,方案的ID已自动设置为地块ID。 I changed the variable name to "scenario" and the id is not being set up any longer and persist goes as planned 我将变量名称更改为“方案”,并且不再设置ID,并且按计划进行操作

The error occurs because the object has an ID . 发生错误是因为对象具有ID。 Hibernate distinguishes between transient and detached objects and persist works only with transient objects(Objects with no ID). Hibernate可以区分临时对象和分离对象,并且持久化仅适用于临时对象(无ID的对象)。 If persist concludes the object is detached (which it will because of the ID ), it will return that error 如果persist断定对象已分离(由于ID,它将分离),它将返回该错误

org.hibernate.PersistentObjectException: detached entity passed to persist org.hibernate.PersistentObjectException:分离的实体传递给持久化

I think you need to use saveOrUpdate() instead of save() / persist() 我认为您需要使用saveOrUpdate()而不是save() / persist()

See this link and this answer 看到这个链接这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM