为什么在同一事务中@PostLoad之后JPA @PreUpdate不调用?

时间:2019-03-29 13:24:46

标签: spring hibernate spring-boot jpa spring-data-jpa

我的Bean类是:

package com.abcfinancial.api.generalledger.fee.domain;

import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;

import javax.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

@Data
@Entity
@Table( name = "fee" )
@EntityListeners( FeeListner.class )
public class Fee
{
    @Id
    @GeneratedValue( strategy = GenerationType.AUTO )
    @Column( name = "fee_id" )
    private UUID feeId;

    @Column( name = "accn_id" )
    private UUID accountId;

    @Column( Name = "fee_created" )
    @CreationTimestamp
    private LocalDateTime created;

    @Column( name = "fee_deactivated" )
    private LocalDateTime deactivated;

    @Column( name = "fee_modified" )
    @CreationTimestamp
    private LocalDateTime modified;

    @Column( name = "fm_key" )
    private String feeMode;

    @Column( name = "ft_key" )
    private String feeType;

    @Column( name = "ftt_key" )
    private String feeTransactionType;

    @Column( name = "fvt_key" )
    private String feeValueType;

    @Column( name = "fee_value" )
    private BigDecimal feeValue;

    @Transient
    private boolean active;

    @PostLoad
    @PrePersist
    @PreUpdate
    private void postLoad()
    {
        if( this.deactivated == null )
        {
            this.active = true;
        }
    }
}

在上述课程中,我想使用deactivated变量使收费活动。如果停用了费用,则费用是无效的,反之亦然。此概念在创建,删除和获取费用的情况下有效,但不适用于更新费用。

在更新费用中,我们通过ID来获取费用,并在同一笔交易中更新一个变量。以下是我的更新费用代码(服务方法):

@Transactional
public UpdateFeeVO updateFeeDetails( UpdateFeeRequestVO updateFeeVO, UUID feeId )
{
    Optional<Fee> feeOptional = feeRepository.getDetailsByFeeId( feeId );//After this line feeOptional.get().getActive() give true
    if( feeOptional.isPresent() )
    {
        //update some variable
        feeRepository.save( feeOptional.get() );
        log.trace( "Fee: {}",feeOptional.get() );// feeOptional.get().getActive() give false
    }
}

我不想更改服务文件

2 个答案:

答案 0 :(得分:1)

我认为您不需要该活动变量和此postLoad方法。

激活变量始终不会保留。

只需将isActive()的获取者更改或覆盖为

public boolean isActive(){
   return deactivated == null || deactivated.isAfter(LocalDateTime.now());
}

答案 1 :(得分:0)