Answer the question
In order to leave comments, you need to log in
How to pull related entity in Hibernate?
Hello, I want to understand how to work with related entities in Hibernate
Here is an example we have two 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
}
@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
}
<mapping class="com.example.auth.entity.user.User"/>
<mapping class="com.example.auth.entity.GrowBox"/>
@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;
}
Answer the question
In order to leave comments, you need to log in
Asked the same question on a bourgeois stackofferflow
https://stackoverflow.com/questions/56886968/how-s...
String hqlQuery = "from GrowBox gb where gb.responsibleUser.id =: userId";
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question