Hibernate不会在具有复合ID的实体上填充生成的@CreationTimestamp和@UpdateTimestamp

时间:2019-03-13 11:13:01

标签: java hibernate jpa hibernate-annotations

我正在使用JPA和Hibernate 5。

通常,如果Hibernate保存了一个Java Bean,我希望所有持久化的值(包括ID,数据库或代码生成的值)都填充在原始实体上。通过说“生成的值”,我指的是通过@PerPersist方法(如果我是通过这种方式执行的UUID)来引用生成的ID,或通过数据库中的专用序列引用@GeneratedValue;另外,我指的是@CreationTimestamp@UpdateTimestamp生成的时间戳,它们负责在插入/更新行时在字段中填充时间戳。

并且当实体具有简单的@Id字段时,此方法才有效。

但是,当我有一个带有复合ID的bean,并且复合ID是另一个@Embeddable bean时,创建时间戳和更新时间戳正确完成并保存在DB中,但没有填充到原始实体中。

具有复合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;
}

可嵌入的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;
}

在测试中,我首先保存一个Provider,然后保存一个Merchant,然后取出ID,并将其分配给ID bean,并将其设置为BalanceTransaction,然后保存到数据库。

@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);
}

请注意,MerchantProvider都具有Short类型的@Id,这是由Postgresql数据库的专用序列生成的。而且,它们都具有以下字段:

例如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))
        );
    }

}

保存后,将创建时间戳并将其填充到原始实体中。

但是,这似乎不适用于该测试:

@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);

}

如果我这样做

BalanceTransaction saved = serviceClient.saveBalanceTransaction(balanceTransaction);

并检查saved,此测试不会失败。

所以:

将保存的值填充到原始实体中,这不是标准吗?很容易失败吗?似乎它不能保证任何事情。

0 个答案:

没有答案