1

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.

adrift
  • 637
  • 2
  • 10
  • 34
  • 1
    You want update or insert? Your question title and content is not saying same thing. – Pau Kiat Wee Jun 12 '12 at 11:19
  • To insert - persist(), to update - merge(). Merge() is for detached objects, for persistent you do nothing before committing a transaction. – d1e Jun 12 '12 at 11:22

1 Answers1

3

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.

ftr
  • 2,105
  • 16
  • 29
  • It's strange, but after entityManager.persist(st) gets executed triggerId is populated with ID of previously added record and nothing is added or updated in database. And no any exceptions are thrown. I need this ID later, to insert a referenced record to another table. – adrift Jun 12 '12 at 11:22
  • Maybe it's worth looking into the trigger? – maksimov Jun 12 '12 at 11:27