Spring Data JPA Many to Many save to set

8.1k views Asked by At

I have the problem, that I have a Many-to-Many relationship and i want to add or Remove items from the set. *

@Entity
@DiscriminatorValue("P")
public class Patient extends User{
    private String firstName;
    private String lastName;
    @Embedded
    private Address address;

    @ManyToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
    @JoinTable(name="PatientOrganisation", joinColumns = {@JoinColumn(name="patientId")}, inverseJoinColumns = {@JoinColumn(name="organisationId")})
    private Set<Organisation> organisations = new HashSet<Organisation>();
}

*

@Entity
@DiscriminatorValue("O")
public class Organisation extends User{

    @Column(name="organisationName")
    private String name;

    @ManyToMany(mappedBy="organisations", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
    private Set<Patient> patients = new HashSet<Patient>();
    }

This are my two entities.

Now i tried to write a custom save methode like this

public interface OrganisationRepository extends

PagingAndSortingRepository<Organisation, Long>{

    @Query (value="insert into patient_organisation(patient_id, organisation_id) values ([?1], [?2])", nativeQuery=true)
    Organisation addPatient(Long patientId, Long organisationId);
}

But that didnt work i get this error.

Can not issue data manipulation statements with executeQuery().

Is there a smarter way to do this or can someone help me with that error.

Thanks, Chris

1

There are 1 answers

1
Viktor Chvátal On BEST ANSWER

I am not quite sure why you decided to write native query for this, I would let the ORM to add the record to many to many just by adding the user into organisation's set of users like this:

@Service
@Transactional
public class OrganisationDataService {
    @Autowired
    CrudRepository<Organisation, Long> organisations;

    @Autowired
    CrudRepository<User, Long> users;

    public void addUserToOrganisation(Long patientId, Long organisationId) {
        Organisation organisation = organisations.findOne(organisationId);
        User user = users.findOne(patientId);
        organisation.getPatients().add(user);
        organisations.save(organisation);
    }
}