Answer the question
In order to leave comments, you need to log in
Spring. How to get an entity with a specific field value?
Hello!
I have a House, which has a bunch of other child entities, including Docs. The problem is that there are documents of several different types. Right now I only want to work with one particular one, but I will need more in the future.
The database already has data for other types and, of course, the form crashes when you try to open it - after all, more than 1 result is returned. I changed the connection to ManyToOne, in House I made a List instead of a single value.
But I don’t understand where and how to separate the unnecessary ones. Now the code looks like this:
HOUSE
@Data
@Entity
@Table(schema = "public", name = "House")
public class House implements Serializable {
@Column(name = "House_ID")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// всякие другие поля дома и другие дочерние сущности
@OneToMany(mappedBy = "house", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private List<HouseDoc> houseDocs;
@Entity
@Table(name = "House_Doc", schema = "public")
@Data
public class HouseDoc implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Pkey_id")
private Integer id;
@Column(name = "Doc_type")
private int docType;
// всякие другие поля документов
@ManyToOne
@JoinColumn(name = "House_ID", referencedColumnName = "House_ID")
protected House house;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HouseFullProjection extends HouseProjection {
private List<HouseDoc> houseDocs;
@Data
public class HouseDocProjection implements Serializable {
private Integer id;
protected int docType;
}
@RequestMapping(value = "/houses/edit/{id}")
public ModelAndView editCard(@PathVariable("id") Integer id) {
House house = service.getHouse(id);
house.getWindowOptions(); // это всякие другие дочерние сущности, с ними всё ок
<b>house.getHouseDocs();</b> // вот тут мне нужен 1 документ, а не пачка
return editCard(house);
}
Answer the question
In order to leave comments, you need to log in
Hello!
Why don't you use jpql (jpa) capabilities?
I don't see all your code, in particular @Service & @Repository
Approximately, you need to do something like this...
Add to the repository
@Query(SELECT House h FROM ... WHERE h.housId = ?1 AND h.housedoc.docType = ?2)
House findHouseByIdAndHouseDocByDocType(Long houseId, int docType)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question