JPA passing parameter as Set
i want to pass a parameter in the jpql as set in an update statement. here is the statement:
Query query = entityManager.createQuery("UPDATE Patient patient SET "
+"patient.surname=:surname, "
+"patient.firstname=:firstname, "
+"patient.homeAddress=:homeAddress, "
+"patient.relatedPersons=:relatedPersons, "
+"patient.hospital=:hospital "
开发者_如何学C +"WHERE patient.id=:id");
query.setParameter("surname", updatablePatient.getSurname());
query.setParameter("firstname", updatablePatient.getFirstname());
query.setParameter("homeAddress", updatablePatient.getHomeAddress());
query.setParameter("relatedPersons", updatablePatient.getRelatedPersons());
query.setParameter("hospital", updatablePatient.getHospital());
query.setParameter("id", id);
but i get the following error:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [****] was not matching type [java.util.Set]; nested exception is java.lang.IllegalArgumentException: Parameter value [****] was not matching type [java.util.Set]
any help would be really appreciated.
thanks in advance
Update statements in JPQL are rarely used, and should be used for batch updates, but not simply to update one entity. They translate directly to SQL, and you can't update a patient and all his related persons like this in SQL. The same goes for JPQL.
To do what you want to do, just get the patient from the database, and set the new properties into the loaded patient :
Patient p = (Patient) entityManager.find(Patient.class, id);
p.setSurname(updatablePatient.getSurname());
p.setRelatedPersons(updatablePatient.getRelatedPersons());
// ... set other properties
Or, if the updatable patient is a detached copy of the patient to update, and thus has the same ID,
Patient p = (Patient) entityManager.merge(updatablePatient);
The whole point of JPA (or at least one of its points) is to be able to use and modify an object graph rather than use queries to create and update data in database.
There is no support for updating set (or in general any collection valued field) via JPQL. In JPA 2.0 specification this is spelled as follows:
update_clause ::= UPDATE entity_name [[AS] identification_variable]
SET update_item {, update_item}*
update_item ::= [identification_variable.]
{state_field | single_valued_object_field} = new_value
For more details: JPQL BNF
精彩评论