Alex
Alex

Reputation: 616

JPA 2 merge is inserting instead of updating when primary key is UUID

For one of my entities I want to use UUID as primary key instead of a Long. The entity extends AbstractEntityUUID:

@MappedSuperclass
public abstract class AbstractEntityUUID implements Serializable {

    private static final long serialVersionUID = 40076842287035126L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    public UUID getId() {
        return id;
    }

    @Override
    public int hashCode() {
        if (getId() != null) {
            return getId().hashCode();
        }
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        AbstractEntityUUID other = (AbstractEntityUUID) obj;
        if (getId() == null || other.getId() == null) {
            return false;
        }
        if (!getId().equals(other.getId())) {
            return false;
        }
        return true;
    }

}

The entity itself is:

@Entity
@Table(schema = "schemaName", name = "order")
@DynamicUpdate
public class Order extends AbstractEntityUUID {

    private static final long serialVersionUID = 6358231835578038565L;

    @Column(precision = 10, scale = 2)
    protected BigDecimal itemPrice;

    @Temporal(TIMESTAMP)
    @Basic(fetch = LAZY)
    protected Date purchaseDate;

    // other properties and getters & setters ...

}

The persist method works fine:

Order order = new Order();
order.setItemPrice(BigDecimal.ONE);
order = getEM().persist(order);

A new row is created on the database table with the correct info. When there is a merge later on is when the issue occurs:

order.setPurchaseDate(new Date());
order = getEM().merge(order);

The previous row seems to be left unchanged and a new one is created with a new primary key which includes the price and date.

When the primary key is Long with GenerationType.IDENTITY the row is updated correctly instead and it works as expected.

This is run on a WildFly 16 server on an ejb 3 bean. The Hibernate implementation seems to be 5.3.9. The DB is MySQL server 5.7.

It is fine if Java generates the UUID values and I would rather not change that unless it is required to make the entity work with a UUID as primary key.

Upvotes: 0

Views: 1278

Answers (1)

Jens Thielscher
Jens Thielscher

Reputation: 11

Are you sure that persist is working as expected when MySql generates the UUID? Is the id of the entity the same as the id inserted into the database?

Upvotes: 1

Related Questions