问题
EntityManager.persist() function is trying to update a existing record, but I always need to insert a new one. How to achieve this?
Part of Entity bean:
@Entity
@Table(name="SYNC_TRIGGER", schema="ETL")
public class SyncTrigger implements Serializable {
@Id
@Column(name="ID")
@SequenceGenerator(name = "TRIGGER_SEQ", sequenceName = "ETL.TRIGGER_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TRIGGER_SEQ")
private Long triggerId;
......
Part of Stateless bean, which persists the record:
@Stateless
public class TriggerPersister {
@PersistenceContext(unitName="syncTriggerDS")
protected EntityManager entityManager;
public <T extends GenericTrigger> void persistTrigger(SyncTrigger
st, T concreteTrigger){
entityManager.persist(st);
.........
UPD: Before entityManager.persist(st) is executed st.triggerId value is null, but after - id of previously added record is assigned to this field.
回答1:
EntityManager.persist() always tries to create a new managed object. It throws an EntityExistsException if you call it on an already managed entity.
You'd have to use merge() for updates.
See the javadoc for both methods.
来源:https://stackoverflow.com/questions/10995533/ejb-jpa-how-to-use-entitymanager-persist-to-always-insert-a-new-record-not-u