@Query内的JPA Join查询

时间:2019-04-30 05:25:46

标签: spring hibernate spring-boot jpa spring-data-jpa

我有三个模型类,分别是-用户,菜单,子菜单。

@Data
@Entity
@Table(name = "CBR_USER")
public class User {
    @Id
    @GeneratedValue
    @Column(name = "CBR_USER_ID")
    private Integer cbrUserId;
    @Column(name = "LOG_IN_ID")
    private String logInId;
    private String userId;
    private String password;
    @Column(name = "FULL_NAME")
    private String FULL_NAME;
    private String EMAIL;
    private String PHONE;
    private Integer ROLE_ID;
    private String DESIGNATION;
    private String branchId;
    private Integer IS_VALID;

    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(FetchMode.SELECT)
    @JoinTable(name = "Conf_menu_Access", joinColumns = @JoinColumn(name = "CBR_USER_ID"), inverseJoinColumns = @JoinColumn(name = "id"))
    private List<Menu> menuList;

} 

菜单类为:

   @Data
    @Entity
    @Table(name = "CONF_MENU")
    public class Menu {
        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_menu")
        @SequenceGenerator(name = "seq_menu", sequenceName = "seq_menu", allocationSize = 1)
        private Integer id;
        private String name;
        private String url;
        private Integer accessBy;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "menuId")
        private List<SubMenu> menuList;

    }

,子菜单类为

@Data
@Entity
@Table(name = "conf_sub_menu")
public class SubMenu {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_sub_menu")
    @SequenceGenerator(name = "seq_sub_menu", sequenceName = "seq_sub_menu", allocationSize = 1)
    private Integer id;
    @Column(name = "MENU_ID")
    private Integer menuId;
    private String name;
    private String url;
}

编译我的代码后,它将生成另一个映射表名称为

  

Conf_menu_Access

此表映射用户可访问菜单,它在User类中定义。

现在我需要实现一个

的sql查询
SELECT ID ,NAME,
    CASE 
        WHEN (SELECT ID FROM CONF_MENU_ACCESS WHERE CBR_USER_ID = 150 AND ID = CMA.ID )>0 THEN 1 
        ELSE 0 
    END AS ACCESSBY 
FROM CONF_MENU CMA ORDER BY ID ASC 

我想在 @Query 标记中编写此查询,任何人都可以帮助我该怎么做……

1 个答案:

答案 0 :(得分:0)

您可以使用

@Query(value = "SELECT ID ,NAME,
    CASE 
  WHEN (SELECT ID FROM CONF_MENU_ACCESS WHERE CBR_USER_ID = 150 AND ID = CMA.ID )>0 
THEN 1  ELSE 0 
    END AS ACCESSBY 
FROM CONF_MENU CMA ORDER BY ID ASC", nativeQuery = true)

正在使用的列名称可能与数据库中的列名称匹配,而即将出现的错误可能是您传递的列名称属于实体字段。