内部连接在spring引导数据jpa中

时间:2017-02-07 17:16:00

标签: spring-boot spring-data-jpa

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

  1. 表包含group_id(主键),group_name,group_active(值= Y / N)。 理想情况下,组表只能有一行,其中group_active为'Y',其余行应为'N'<​​/ p>

  2. 用户表包含user_id(主键),user_name,group_id(来自组的外键)。

  3. 以下是我的实体类

    组:

    @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的正确方法是什么,以便我总是找回属于具有名称的活动组的一个用户?

2 个答案:

答案 0 :(得分:0)

我根据您的设置做了一些测试,解决方案需要使用过滤器(假设只有一个Group的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')")

答案 1 :(得分:0)

尝试一下

node -v