gpt4 book ai didi

java - Spring Data JPA @Query 注解的问题(SQL 语法错误)

转载 作者:行者123 更新时间:2023-12-02 10:39:46 25 4
gpt4 key购买 nike

编辑:我想检查某个用户是否在组中拥有权限。如果有更好的解决方案而不查询他的所有权限请告诉我。

以下查询给了我一个我无法理解的错误:

@Repository
public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {

@Query("select p from Privilege p " +
"inner join p.userTypes " +
"inner join UserGroup u " +
"where u.user.id=:uid and u.group.id=:gid")
List<Privilege> getPrivilegesOfUser(@Param("uid") Long uid, @Param("gid") Long gid);

}

错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where usergroup1_.user_id=28 and usergroup1_.group_id=18' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]

用户组实体

@Entity
@Table(name = "user_to_group")
public class UserGroup {

@EmbeddedId
private UserGroupId id;

@ManyToOne(fetch = FetchType.LAZY,
cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.REFRESH, CascadeType.PERSIST})
@MapsId("userId")
@JoinColumn(name = "user_id", insertable = false, updatable = false)
private User user;

@ManyToOne(fetch = FetchType.LAZY,
cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.REFRESH, CascadeType.PERSIST})
@MapsId("groupId")
@JoinColumn(name = "group_id", insertable = false, updatable = false)
private Group group;

@ManyToOne(fetch = FetchType.LAZY,
cascade = {CascadeType.DETACH, CascadeType.MERGE,
CascadeType.REFRESH, CascadeType.PERSIST})
@JoinColumn(name = "user_type_id")
private UserType userType;

@Column(name = "is_blocked",
insertable = false)
private boolean isBlocked = false;

我首先在 MYSQL Workbench 中尝试了等效查询,并且工作得很好。 Jpa 存储库实现没有任何内容。这是在 MYSQL 上运行的代码:

select p.name from privilege p 
inner join user_type_to_privilege utp
on p.id=utp.privilege_id
natural join user_to_group utg
where utg.user_id=16 and
utg.group_id=9;

这是我使用的方言:spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect这是过时的还是什么?

最佳答案

问题出在第二个内部联接上。它不明确,不知道要匹配哪一列来进行连接。有效的查询:

@Query("select p from Privilege p " +
"inner join p.userTypes t " +
"inner join UserGroup u on t.id=u.userType.id "+
"where u.user.id=:uid and u.group.id=:gid")
List<Privilege> getPrivilegesOfUser(@Param("uid") Long uid, @Param("gid") Long gid);

关于java - Spring Data JPA @Query 注解的问题(SQL 语法错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53008060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com