I use spring-jpa with hibernate implementation. I use mariadb and I try to do an update subquery
My object structure
@Entity public class Room { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long roomId; @ManyToOne @JoinColumn(name = "appartment_id") private Appartment appartment; } @Entity public class Appartment { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long appartmentId; @OneToMany @JoinColumn(name="appartment_id") private Set<Room> roomList; } update Room r1 set r1.available = :availability where r1.roomId in ( select r2.roomId from Room r2 JOIN r2.appartment a1 WHERE a1.appartmentId = :appartmentId )
I get this error
java.sql.SQLException: Table 'room' is specified twice, both as a target for 'UPDATE' and as a separate source for data
This is a restriction in MySQL:-
http://dev.mysql.com/doc/refman/5.7/en/update.html
You cannot update a table and select from the same table in a subquery.
There is a fudge you can do sometimes do to hide the sub query in a a further level of sub query that might work. Something like this (not tested):-
UPDATE Room r1 SET r1.available = :availability WHERE r1.roomId IN SELECT roomId FROM ( SELECT r2.roomId FROM Room r2 JOIN r2.appartment a1 WHERE a1.appartmentId = :appartmentId )
Note that your query possibly has an error. In the sub query you are joining the table Room aliased as r2 to a table called appartment on a database called r2. Also your sub query does a JOIN without a join condition.
However you can quite possibly just do the join in the UPDATE statement without the need for a sub query:-
UPDATE Room INNER JOIN r2.appartment a1 ON Room.roomId = a1.roomId SET r1.available = :availability WHERE a1.appartmentId = :appartmentId