Jpa how to refresh entity after partial update

34 Views Asked by At

Hi I have an entity with a many to one. I used an old technic the object is in read only and i use the id for update.

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "type_hour_id", insertable = false, updatable = false)
    @ToString.Exclude
    private TypeHourEntity typeHour;

    @Column(name = "type_hour_id")
    private Long typeHourId;

When i set the id save the main entity, the dabase change properly but typeHour object not. I need to use entityManager.refresh to update it.

Same issue if i use on repository a query to update one column

    @Modifying(flushAutomatically = true, clearAutomatically = true)
    @Query("UPDATE DayEntity d SET d.validate = NOT d.validate WHERE d.id = :id")
    int toggleValidate(@Param("id") Long id);

if i use toggleValidate the dabase change properly and if i use a findById just after the property validate is not changed on entity.

Once again i need to use entityManager.refresh to update it.

It exist another way to get the entity updated automatically?

For the first one i can use the typeHour in read write and remove the id, but like that i have to perfom a typehourrepository.findById each time i want to change the object. That is not necessary.

If no solution i can add a superclass on all entities and add:

    @PersistenceContext
    @Transient
    private EntityManager entityManager;
    protected void refresh(){
        entityManager.refresh(this);
    }

is it a good way?

0

There are 0 best solutions below