I'm writing a Spring Boot app using an H2 file-based database. I have a few threads running in parallel, so I'm trying to find the best way to add elements to my Entity's embedded Set of Strings - an ElementCollection.
Fetching the full entity just to modify one field and save the whole entity, even though I've only changed one field, seems both clunky and risky - what if another thread is changing something else about the same entity - I wouldn't want to overwrite those unrelated changes.
Say I have an entity Product:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Product {
@Id
private int id;
private String description;
private boolean soldOnline;
@ElementCollection(fetch = EAGER)
private Set<String> statesWhereAvailable = new HashSet();
}
And I have one thread going through and initializing the boolean soldOnline flag, and another thread going through and adding to the set of distinct states where people can purchase this product in-store. In the event of concurrent updates to the same Product, I wouldn't want the second thread to undo changes made in the first, because it happened to fetch the Entity before the first thread finished saving.
I'm hoping there's a way to write a Jpa Repository query to update that ElementCollection, but I can't find any examples anywhere. I'm hoping to be able to write something like this:
@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
@Transactional
@Modifying
@Query(value = "update Product p " +
"set i.statesWhereAvailable = i.statesWhereAvailable + :state " +
"where p.id = :id")
void addVendorToRelatedVendors(@Param("id") int id,
@Param("state") String state);
}
Any advice would be really appreciated!