EJB/JPA: How to use EntityManager.persist() to always INSERT a new record, not update

我的梦境 提交于 2020-01-14 03:28:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!