我坚持将实体与其集合中的一个独立子实体合并的问题。它抛出异常: org.hibernate.PersistentObjectException:传递给persist的分离实体:com.adastragrp.cmsms.data.SeedNumber
你可以在这个“test()”方法中看到我从DB获取一些Queue并取其子。当它们被发送到“saveQueue()”方法时,它们处于分离状态。在这个方法中,我将它们添加到其他队列。合并此队列时,hibernate会抛出异常。
我怎样才能让它发挥作用?谢谢你的任何答案或解释。
private void test() {
List<SeedNumber> list = loadQueue();
saveQueue(list);
}
@Transactional
private List<SeedNumber> loadQueue() {
return queueDAO.find("SECONDARY").getSeedNumbers();
}
@Transactional
private void saveQueue(List<SeedNumber> detachedSeeds) {
Queue q = queueDAO.find("DEFAULT");
List<SeedNumber> seeds = new ArrayList<>();
SeedNumber sn = new SeedNumber();
sn.setPhoneNumber("123456");
sn.setQueue(q);
seeds.add(sn);
for(SeedNumber s : detachedSeeds) {
s.setQueue(q);
seeds.add(s);
}
q.setSeedNumbers(seeds);
q = queueDAO.save(q);
}
DAO代码:
public Queue save(Queue entity) {
if (entity == null) {
LOG.info("queue is null");
return null;
}
if (getEntityManager().contains(entity)) {
return entity;
}
entity = getEntityManager().merge(entity);
return entity;
}
这是父类:
@Entity
@Table(name = "CMSMS_QUEUE")
public class Queue {
@Id
@Column(name = "ID", length = 40)
private String id;
@OneToMany(mappedBy = "queue", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<SeedNumber> seedNumbers;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<SeedNumber> getSeedNumbers() {
return seedNumbers;
}
public void setSeedNumbers(List<SeedNumber> seedNumbers) {
this.seedNumbers = seedNumbers;
}
}
这是儿童班:
@Entity
@Table(name = "CMSMS_SEED_NUMBER")
@SequenceGenerator(name = "SeedNumberSeq", sequenceName = "CMSMS_SEED_NUMBER_SEQ", allocationSize = 1)
public class SeedNumber {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SeedNumberSeq")
@Column(name = "ID")
private Long id;
@Column(name = "PHONE_NUMBER")
private String phoneNumber;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "QUEUE_ID")
private Queue queue;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Queue getQueue() {
return queue;
}
public void setQueue(Queue queue) {
this.queue = queue;
}
}
答案 0 :(得分:1)
我认为以下代码存在问题:
mWebView.getSettings().setAppCachePath(mContext.getCacheDir().getPath());
如果您希望if (getEntityManager().contains(entity)) {
return entity;
}
entity = getEntityManager().merge(entity);
return entity;
传播到种子编号列表,则不应跳过对cascade=MERGE
的调用。
merge
:
saveQueue
作为旁注,将private void saveQueue(List<SeedNumber> detachedSeeds) {
Queue queue = queueDAO.find("DEFAULT");
SeedNumber sn = new SeedNumber();
sn.setPhoneNumber("123456");
sn.setQueue(q);
seedNumberDao.saveSeed(sn);
for (SeedNumber seed : detachedSeeds) {
seed.setQueue(queue);
seedNumberDao.saveSeed(seed);
}
}
放在私有方法上没有任何效果。