I want to understand how to work with related entities in Hibernate. There are two related entities:
@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
}
and
@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
}
I have registered mapping using annotations. Hope it is correct. And I want to find box by user Id, but don't know how HQL query should be written. 'Cause there is no "user_id" field in my Box Class. Instead there is "User responsibleUser" field. And smth like this won't work(should not)
@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;
}
一个HQL查询将是
String hqlQuery = "from GrowBox gb where gb.responsibleUser.id =: userId";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.