gpt4 book ai didi

java - PersistentObjectException : detached entity passed to persist: com. 边缘.le.domain.Tag

转载 作者:太空宇宙 更新时间:2023-11-04 11:39:58 25 4
gpt4 key购买 nike

我有一个 Goal 实体,它与 Tag 具有多对多关系。这里的Goal是我拥有的实体。我正在使用 JPA 来坚持。当我使用现有的 Tag 保存 Goal 时,它给出了 PersistentObjectException 。其他场景,例如使用新的 Tag 的 New Gaol 、使用现有的 Tag 编辑现有的 Goal 、使用新的 Tag 的现有 Goal 都工作正常。下面是我的实体结构:

目标.java

@Entity
@Table(name = "goal")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "goal")
public class Goal implements Serializable {

private static final long serialVersionUID = 1L;

@ManyToMany(cascade = {
CascadeType.MERGE,
CascadeType.PERSIST,
},targetEntity = Tag.class)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "goal_tag",
joinColumns = @JoinColumn(name="goals_id", referencedColumnName="ID"),
inverseJoinColumns = @JoinColumn(name="tags_id", referencedColumnName="ID"))
private Set<Tag> tags = new HashSet<>();

//getters & setters

标签.java

 @Entity
@Table(name = "tag")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "tag")
public class Tag implements Serializable {

private static final long serialVersionUID = 1L;

@Id
private String id;

@ManyToMany(mappedBy = "tags")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Goal> goals = new HashSet<>();

//getters & setters

GoaServiceImpl.java save() 方法

 public class GoalServiceImpl implements GoalService{

private final Logger log = LoggerFactory.getLogger(GoalServiceImpl.class);

@Inject
private GoalRepository goalRepository;

@Inject
private GoalMapper goalMapper;

@Inject
private GoalSearchRepository goalSearchRepository;

@Inject
private TagRepository tagRepository;

/**
* Save a goal.
*
* @param goalDTO the entity to save
* @return the persisted entity
*/
public GoalDTO save(GoalDTO goalDTO) {
log.debug("Request to save Goal : {}", goalDTO);
Goal goal = goalMapper.goalDTOToGoal(goalDTO);
goal = goalRepository.save(goal);
GoalDTO result = goalMapper.goalToGoalDTO(goal);
//goalSearchRepository.save(goal);
return result;
}

}请帮帮我。

最佳答案

当您尝试使用save时,持久性提供程序尝试级联的操作是PERSIST。当您尝试保留一个已存在的分离实体时,您最终会遇到该异常。

由于您在该关系上设置了 MERGE 级联选项,因此我建议使用合并而不是持久:

goal = goalRepository.merge(goal);

现在,如果您的目标是一个新实体,它将被持久化,并且分离的标签实体将被合并(如果持久化提供程序发现状态发生变化,则会更新)。

关于java - PersistentObjectException : detached entity passed to persist: com. 边缘.le.domain.Tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42922783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com