我使用JPA与休眠提供程序。我的继承人部分代码:JPA合并()分离实体插入时,它存在
@Entity
@IdClass(xxxPK.class)
@NamedQueries({
...
})
@Inheritance(strategy = InheritanceType.JOINED)
public class xxx extends AbstractEntity {
public static final String GET_TRADES = "getInstruments";
public static final String GET_STRUCTURE = "getStructure";
public static final String GET_ALL = "getAllTrades";
@Column(nullable = false)
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "xxx")
@SequenceGenerator(name = "xxxx", sequenceName = "xxxxS", allocationSize = 1)
private Long systemId;
@Id
@Column(nullable = false)
private Integer version;
//////
而一个后代:
@Entity
@PrimaryKeyJoinColumns(
{
@PrimaryKeyJoinColumn(name = "systemId"),
@PrimaryKeyJoinColumn(name = "version")
}
)
public class YYY extends xxx {
//////
我创建一个YYY实例和persiti是如我所料。之后,我在每个表中的每一行db:
fx = Persistence.invoke(new Persistence.Invoke<YYY>() {
@Override
public YYY run(EntityManager em) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new ClassPathResource("json/XXX_from.json").getFile()));
} catch (IOException ex) {
System.out.print("File is not found");
}
YYYfx = (YYY) EntityConverter.getConverter(YYY.class).fromJson(reader);
em.persist(fx);
return fx;
}
});
所以,之后,fx被分离,并作为SPEC。赛斯我可以使它在另一个会话通过调用合并()持久的,所以叫它但:
Persistence.invoke(new Persistence.Invoke<Object>() {
@Override
public Object run(EntityManager em) {
fx.setZZZ("A");
em.merge(fx);
return null;
}
});
之后,我有另一行XXX和YYY表与新的主。它看起来像提供程序将fx作为TRANSIENT而不是作为DETACHED然后它就好了 - 它是一个新的对象,我会插入它。 我不知道该怎么做我已经在这样愚蠢的情况下失去了4个小时。请帮忙!
public class Persistence {
private static EntityManagerFactory emf;
public static EntityManagerFactory getEmf() {
return emf;
}
public void setEmf(EntityManagerFactory emf) {
Persistence.emf = emf;
}
public static <T> T invoke(Invoke<T> inv) {
T result = null;
EntityManager em = getEmf().createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
result = inv.run(em);
transaction.commit();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
em.close();
}
return result;
}
public interface Invoke<T> {
public T run(EntityManager em);
}
}