Home > Blockchain >  Update associated object inside Entity via @Query in spring data jpa
Update associated object inside Entity via @Query in spring data jpa

Time:10-25

I want to update an associated object inside Entity via @Query of spring data JPA. Is it possible to do so?

@Entity
@Getter
@Setter
public class Person{
   
   @Id
   private Long id;
   
   @OneToOne
   @NotNull
   @JoinColumn(name = "address")
   private Address address;
}
@Entity
@Getter
@Setter
public class Address{
   
   @Id
   private Long id;
   
   private String state;
}

All the examples that I can see on the internet point to update query with String, int, ... I am looking a way to update the query where I can pass the custom associated objects.

@Modifying
@Query("update Person p set p.address =: address)
void update(@Param(value = "address") Address address)

is it possible? I have tried with EntityManager, save() method of JPA as well, but I am looking for the above kind of JPQL query.

CodePudding user response:

The following will update all Person entities' address.

@Transactional
@Modifying
@Query("update Person p set p.address = :address")
void update(@Param(value = "address") Address address)

Note the @Transactional annotation and make sure that the Address address parameter should not be transient, i.e. should already exist in database and fetch it from there

i.e.

Address address = new Address();
address.setState("blabla");
Address savedAddress = addressRepository.save(address);

personRepository.update(savedAddress); // use the peristed Address entity here.
  • Related