我应该如何获得相关实体?

时间:2019-07-04 11:27:33

标签: java hibernate

我想了解如何在Hibernate中使用相关实体。 有两个相关实体:

@Entity
@Table(name = "usr")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String username;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private String email;

    private boolean active;

    @Enumerated(EnumType.STRING)
    private Role role;

    @OneToMany(fetch = FetchType.LAZY, 
    mappedBy = "responsibleUser", cascade = CascadeType.ALL)
    private List<GrowBox> growBoxes;
    //def-constructor , getters, setters
}

@Entity
@Table(name = "growBoxes")
public class GrowBox {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @Column(nullable = false)
    private Integer length;

    @Column(nullable = false)
    private Integer width;

    @Column(nullable = false)
    private Integer height;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "responsibleGrowBox", cascade = CascadeType.ALL)
    private List<Plant> plants;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "activeGrowBox", cascade = CascadeType.ALL)
    private List<Sensor> sensors;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User responsibleUser;
    //def-constructor , getters, setters
}

我已经使用注释注册了映射。希望它是正确的。而且我想按用户ID查找box,但是不知道应该如何编写HQL查询。因为我的Box类别中没有“ user_id”字段。而是有“用户负责用户”字段。而且这样的东西是行不通的(不应该)

@Autowired
SessionFactory sessionFactory;

@Override
public List<GrowBox> findByUser(Long userId) {

    Session session = sessionFactory.openSession();
    String hqlQuery = "from GrowBox where user_id =: userId";
    Query query = session.createQuery(hqlQuery);
    List growBoxes = query.getResultList();
    session.flush();
    session.close();
    return growBoxes;
}

1 个答案:

答案 0 :(得分:0)

一个HQL查询应该是

String hqlQuery = "from GrowBox gb where gb.responsibleUser.id =: userId";