Hibernate使用动态参数进行多次连接

时间:2017-04-18 01:22:45

标签: hibernate join parameters criteria

我想得到一个包含0到多个参数的多个连接查询的结果集,我在SQL中的查询是这样的:

    SELECT c.*
      FROM users u
INNER JOIN user_roles ur ON u.username = ur.username
INNER JOIN customer   c  ON u.username = c.customer_id;

下图显示了表之间的关系; tables

实体定义如下:

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column(name = "username", unique = true, nullable = false, length = 45)
    private String username;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    private Customer customer;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<UserRole> userRole = new HashSet<UserRole>(0);

    //getter & setters
}


@Entity
@Table(name = "CUSTOMER")
public class Customer {
    @Id
    @Column(name = "customer_id")
    @GeneratedValue(generator = "gen")
    @GenericGenerator(name = "gen",
            strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
    private String id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private User user;

    //getter & setters
}

@Entity
@Table(name = "user_roles")
public class UserRole {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "user_role_id", unique = true, nullable = false)
    private Integer userRoleId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "username", nullable = false)
    private User user;

    @Column(name = "role", nullable = false, length = 45)
    private String role;

    //getter & setters
}

我已经读过您可以使用条件加入列,但我还没有成功。我怎样才能实现它?

1 个答案:

答案 0 :(得分:0)

我得到了答案:

        Criteria criteria = session.createCriteria(UserRole.class,"userRole")
                            .createCriteria("user","user")
                            .createCriteria("customer","customer");
        criteria.add(Restrictions.eq("user.enabled", enabled));

        if(userName!=null){
            criteria.add(Restrictions.eq("user.username", userName));
        }if(role!=null){
            criteria.add(Restrictions.eq("userRole.role", role));
        }if(fName!=null){
            criteria.add(Restrictions.eq("customer.customerFirstname", fName));
        }if(lName!=null){
            criteria.add(Restrictions.eq("customer.customerLastname", lName));
        }
        List<UserRole> results = criteria.list();