Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't JpaRepository update my entity?

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.

like image 712
Artegon Avatar asked Sep 14 '25 14:09

Artegon


1 Answers

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.

like image 173
Quinton Delpeche Avatar answered Sep 16 '25 03:09

Quinton Delpeche