gpt4 book ai didi

spring-boot - Spring Boot 数据 jpa 中的内连接

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

我正在使用 spring boot data jpa 1.4,我对它很陌生。
我的表定义是 here .它相当简单,有 2 个表(组和用户)。

  • 表包含 group_id(primary key), group_name, group_active(values=Y/N)。
    理想情况下,组表可以只有一行将 group_active 设置为 'Y',其余的应该有 'N'
  • 用户 表包含 user_id(主键)、user_name、group_id(来自组的外键)。

  • 以下是我的实体类

    群:
    @Entity
    @Table(schema = "HR", name = "GROUPS")
    public class Group {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "GROUP_ID")
    private Long id;

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

    @Column(name = "GROUP_ACTIVE")
    private String active;

    用户:
    @Entity
    @Table(schema = "HR", name = "USERS")
    public class User {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "USER_ID")
    private Long id;

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

    @Column(name = "GROUP_ID")
    private Long groupId;

    @ManyToMany
    @JoinTable(
    schema = "HR",
    name = "GROUPS",
    joinColumns = {@JoinColumn(table = "GROUPS", name = "GROUP_ID", insertable = false, updatable = false)},
    inverseJoinColumns = {@JoinColumn(table = "USERS", name = "GROUP_ID", insertable = false, updatable = false)}
    )
    @WhereJoinTable(clause = "GROUP_ACTIVE='Y'")
    private List<Group> group;

    存储库类:
    public interface UserRepository extends CrudRepository<User, Long>{        
    List<User> findByName (String name);
    }

    查询 : 这是我要执行的查询,就是一个简单的内连接。
      SELECT U.*
    FROM HR.USER U, HR.GROUP G
    WHERE U.GROUP_ID=G.GROUP_ID
    AND G.GROUP_ACTIVE='Y'
    AND U.USER_NAME=?

    编写@JoinTable 或@JoinColumn 的正确方法是什么,这样我总是能找回一个属于事件组的名称为 的用户?

    最佳答案

    我已经根据您的设置进行了一些测试,解决方案需要使用过滤器(假设只有一个 Group_Activity = 'Y'):

    集团实体

    @Entity
    @Table(schema = "HR", name = "GROUPS")
    public class Group {

    @OneToMany(mappedBy = "group")
    @Filter(name = "activityFilter")
    private Set<User> users;

    用户实体
    @Entity
    @Table(schema = "HR", name = "USERS")
    @FilterDef(name="activityFilter"
    , defaultCondition="group_id =
    (select g.id from groups g where g.GROUP_ACTIVE='Y')")
    public class User {

    @ManyToOne
    @JoinColumn(name = "group_id")
    private Group group;

    查询时
    session.enableFilter("activityFilter");
    session.createQuery("select u from Group g inner join g.users u where u.user_name = :userName");

    另外 如果有许多事件 = 'Y' 的组,请尝试以下操作:
    @FilterDef(name="activityFilter"
    , defaultCondition="group_id in
    (select g.id from group g where g.GROUP_ACTIVE='Y')")

    关于spring-boot - Spring Boot 数据 jpa 中的内连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42096001/

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