WesternGun
WesternGun

Reputation: 12797

Hibernate does not populate generated @CreationTimestamp and @UpdateTimestamp on entity with composite ID

I am using JPA and Hibernate 5.

Normally, if an java bean is saved by Hibernate, I expect all the persisted values, including those generated ones, like ID, by database or by code, are populated on the original entity. By saying "generated values", I am refering either generated ID by @PerPersist method(if is a UUID I do it this way), or @GeneratedValue with a dedicated sequence in database; also, I refer to timestamps generated by @CreationTimestamp and @UpdateTimestamp, who are responsible for filling a timestamp into a field when a row is inserted/updated.

And this actually works when the entity has simple @Id field.

But, when I have a bean with composite id, and when the composite id is another @Embeddable bean, the creation timestamp and update timestamp is done correctly and persisted in DB, but not populated into the original entity.

The entity with composite ID:

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import java.time.OffsetDateTime;

@Entity
@Table(name = "balance_transaction")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class BalanceTransaction {

    @EmbeddedId
    private CompositeIdMerchantProvider compositeIdMerchantProvider;

    @Column(name = "rate")
    private Integer rate;

    @CreationTimestamp
    @Column(name = "created")
    private OffsetDateTime created;

    @UpdateTimestamp
    @Column(name = "modified")
    private OffsetDateTime modified;
}

The embeddable id bean:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Embeddable
@EqualsAndHashCode
public class CompositeIdMerchantProvider implements Serializable {

    @Column(name = "merchant_id")
    private Short merchantId;

    @Column(name = "provider_id")
    private Short providerId;
}

In the test, I first save a Provider, then a Merchant, then take the ID out, and assign them to the ID bean, and set it to BalanceTransaction, and save it to DB.

@Before
public void setup() {
    resetMerchant(); // create instance, set values, etc.
    resetProvider(); // create instance, set values, etc.
    resetBalanceTransaction(); // create instance, set values, etc.
    merchantRepository.save(merchant); // NOTE: here `merchant` has all the values saved to DB; I don't have to assign the returned one to another entity of type `Merchant`, i.e., they are populated correctly.
    providerRepository.save(provider); // NOTE: this also applies to `provider`
    composite.setProviderId(provider.getId());
    composite.setMerchantId(merchant.getId());
    balanceTransaction.setCompositeIdMerchantProvider(composite);
}

Note that Merchant and Provider both have a Short type @Id, generated by a dedicated sequence of a Postgresql database. And, they both have these fields:

For example, Merchant:

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@Entity
@Table(name = "merchant")
@EqualsAndHashCode(exclude = {"id", "transactions"})
@ToString(exclude = {"transactions"})
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Merchant implements Serializable {
    @Id
    @SequenceGenerator(name="merchant_id_seq", allocationSize=1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="merchant_id_seq")
    @Column(name = "id")
    private Short id; // limited possibilities

    @NotNull
    @NotEmpty
    @Size(max = 45)
    @Column(name = "name")
    private String name; // mandatory, max 45 characters

    @Column(name = "status")
    private Boolean status; // whether merchant is active or not

    @CreationTimestamp
    @Column(name = "created")
    private OffsetDateTime created;

    @UpdateTimestamp
    @Column(name = "modified")
    private OffsetDateTime modified;

    @OneToMany(mappedBy = "merchant", fetch = FetchType.LAZY) // the name of property at "many" end
    private Set<Transaction> transactions;


    /**
     * Add Transaction to the set; must be called after any of two constructors,
     * because we need to initialize the set first.
     * @param t Transaction entity to add
     */
    public void addTransaction(Transaction t) {
        if (transactions == null) {
            transactions = new HashSet<>();
        }
        this.transactions.add(t);
        t.setMerchant(this);
    }

    /**
     * Remove an <code>Transaction</code> from the list of this class.
     * Caution: {@link Set#iterator()#remove()} does not work when iterating. We must
     * construct a new Set and {@link #setTransactions(Set)} again.
     * @param t the <code>Transaction</code> to remove.
     */
    public void removeTransaction(Transaction t) {
        setTransactions(
                transactions.stream().filter(x -> !x.equals(t)).collect(Collectors.toCollection(HashSet::new))
        );
    }

}

And when saved, the timestamps are created and populated into the original entity.

But, it seems that this does not work for this test:

@Test
public void givenABalanceTransactionEntity_WhenISaveItIntoDb_ShouldReturnSavedBalanceTransactionEntity() throws IllegalArgumentException {
    //given (in @Before)

    //when
    serviceClient.saveBalanceTransaction(balanceTransaction); // <-------- "balanceTransaction" will not have timestamp populated

    //then
    Assert.assertNotNull(balanceTransaction); // <-------- this line passes
    Assert.assertNotNull(balanceTransaction.getCreated()); // <------- this line does not pass
    Assert.assertNotNull(balanceTransaction.getModified()); // <------- this neither

    // cleanup
    repository.delete(balanceTransaction);

}

If I do

BalanceTransaction saved = serviceClient.saveBalanceTransaction(balanceTransaction);

and check saved, this test does not fail.

So:

populated saved values into the original entity, is not a standard? Is very failure-prone? It seems that it does not guarantee anything.

Upvotes: 1

Views: 2360

Answers (0)

Related Questions