I have such Jpa repository:
public interface BalanceRepository extends JpaRepository<Balance, Long> {
}
As far as I know (and this answer it confirms) entity manager insert new record (when entity is new) and update entity record when is not new.
My entity class hierarchy:
@Entity
@Table(name = "balances")
public class Balance extends BaseEntity {
// omitted
}
and BaseEntity
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties({"handler", "hibernateLazyInitializer"})
public abstract class BaseEntity {
private static Logger LOGGER = LogManager.getLogger(BaseEntity.class);
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
@JsonProperty("id")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isNew() {
return id == null;
}
}
When I save new Balance
entity, new record is inserted but not update is done, why?
Balance bal = new Balance();
bal.setFinalBalance(BigDecimal.TEN);
bal.setUser(user);
bal.setRecordDate(date);
bal.setMinusBalance(BigDecimal.TEN);
bal.setPlusBalance(BigDecimal.TEN);
bal.setTotalBalance(BigDecimal.TEN);
// entity is inserted
balanceRepository.save(bal);
// no update...
bal.setFinalBalance(bal.getFinalBalance().add(BigDecimal.TEN));
balanceRepository.save(bal);
Update 1 - When I findOne(Long id)
updated record, value seems to be updated, but value in database is not changed.
Try setting "bal = balanceRepository.save(bal);" ... this will return the saved object and will include the generated id ... when you run the next save, it will know that it is an existing object and will then do an update instead of a save.
If that doesn't work, create a newBalance object, set it on the first save and use it for the second save and setFinalBalance call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With