Armine
Armine

Reputation: 1695

How to force EntityManager.persist() to do only insert and not update

I am trying to insert data into a table having columns (NAME, VALUE) with

EntityManager.persist().

When I persist an entity like ('xx', 'value1') it inserts a new record into the table for that entity. But if I want to persist a new entity like ('xx', 'value2'), the entity is persisted in the place of already existing record.

The questions are:

I found a similar question here but there is no real answer for the question.

Many thanks.

UPDATE: The first column is not a primary key. Instead, the second one is.

Here is the Entity:

@Entity
@Table(name = "TEST_DATA")
public class TestDataEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name = "NAME", nullable = false)
    private String name;

    @Id
    @Column(name = "VALUE", nullable = false)
    private String value;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

And here is the persisting code:

@Transactional
public static void storeTestData(EntityManager em, String name, String value) {
    TestDataEntity entity = new TestDataEntity();
    entity.setName(name);
    entity.setValue(value);

    em.persist(entity);
}

Also, there is another question, which is described here.

Upvotes: 2

Views: 3737

Answers (2)

Armine
Armine

Reputation: 1695

The issue is solved this way:

@Transactional
public static void storeTestData(EntityManager em, String name, String value) {
    EntityTransaction transaction = em.getTransaction();

    try {
        transaction.begin();

        TestDataEntity entity = new TestDataEntity();
        entity.setName(name);
        entity.setValue(value);

        em.persist(entity);

        transaction.commit();
    } catch (RuntimeException re) {
        if (transaction != null && transaction.isActive())  {
            transaction.rollback();
        }

        throw re;
    }

This means, that if no explicit transaction is provided, then the existing record is being updated if it has any value matched with the corresponding field value in entity object.

IMHO, this is really strange and not straightforward, since it would be better if it would throw a

javax.persistence.TransactionRequiredException

like it does on update/delete statements.

Upvotes: -1

Eugene Titkov
Eugene Titkov

Reputation: 11

Check if your entity correctly implements equals() and hashCode(), usually this solves the problem

Upvotes: 0

Related Questions