There is an entity:

package com.igorgorbunov3333.core.entities.domain; import javax.persistence.*; @Entity @Table(name = "cases") public class Case { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String caseNumber; private String dataI; private String dataII; private String dataIII; @OneToOne @JoinColumn(name = "id") private Judge judge; @OneToOne @JoinColumn(name = "id") private Lawyer lawyer; @OneToOne @JoinColumn(name = "id") private Client client; @Enumerated(value = EnumType.ORDINAL) private CaseStatus statusI; @Enumerated(value = EnumType.ORDINAL) private CaseStatus statusII; @Enumerated(value = EnumType.ORDINAL) private CaseStatus statusIII; private String document; // геттеры и сеттеры } 

As you can see there are fields judge, lawyer, client (associated). I receive in the service:

 public List<Case> findAll() { Query query = entityManager.createNamedQuery("getAllCases"); return query.getResultList(); } 

I test in a servlet, I receive error NullPointerException. Now the question is: how to organize associations? . The findAll () method returns all objects, but not all fields of entities are found to be the "whole" field lawyer, case, client. That is, I have 20 cases in the table, 10 lawyers. 1 lawyer could conduct more than one case, and findAll (), as I understand, returns the first 10 associated cases with 10 lawyers, and the rest with null-lawyers. I tried both @ManyToOne and @OneToMany, I can not exactly understand what to use.

    1 answer 1

     @ManyToOne private Judge judge;// в классе Case @ManyToOne private Client client;// в классе Case @OneToMany (mappedBy = "judge") private Set<Case> cases = new HashSet<>();// в классе Judge @OneToMany (mappedBy = "client") private Set<Case> cases = new HashSet<>();// в классе Client public List<Case> findAll() { Query query = entityManager.createQuery("select c from Case c left join fetch c.lawyer left join fetch c.judge left join fetch c.client", Case.class); return query.getResultList(); } 

    necessarily redefine hashCode and equals for all classes

    • And if the judges and clients? - Igor Gorbunov
    • one
      updated comment - MrFylypenko
    • Thanks, it's better now! Now at least the application is deployed, not counting javax.persistence.PersistenceException: Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'case0_.judge_id' in 'field list' - Igor Gorbunov
    • check if the Case entity has created such a field in the database? - MrFylypenko
    • Everything worked out. In the database on the site of the objects judge, client, lawyer were respectively integer fields judgeID, clientID, lawyerID. In essence, Case added @JoinColumn () with the name of the field name. Thank you so much) - Igor Gorbunov