Skip to content
Advertisement

Hibernate Join between 2 tables with foreign key

Im trying to get a list with results from join with two tables, but always get error. What i want is List with person and job name

  • Error

    • Cannot invoke “org.hibernate.hql.internal.ast.tree.FromElement.setAllPropertyFetch(boolean)” because “fromElement” is null
  • My tables

    • Person
      • int id
      • text name
      • int job_id (foreign key with table JOB(id))
    • Job
      • int id
      • text name
  • Entities

    @Entity
    @Table(name = "person")
    public class Person{
    
    @Id
    @Column(name = "id")
    int id;
    @Column(name = "name")
    String name;
    @Column(name = "job_id")
    int jobId;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public int getJobId() {
        return jobId;
    }
    
    public void setJobId(int jobd) {
        this.jobId= jobId;
    }
    public String getName() {
        return name;
    }
    
    public void setName(int name) {
        this.name= name;
    }
    
    
    @Entity
    @Table(name = "job")
    public class Job{
    
    @Id
    @Column(name = "id")
    int id;
    @Column(name = "name")
    String name;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(int name) {
        this.name= name;
    }
    
    • DAO
        public class PersonDAO {
        @Autowired
        private SessionFactory sessionFactory;
    
        public void setSessionFactory(SessionFactory sf) {
            this.sessionFactory = sf;
        }
    
        public List<Person> getAllPerson() {
            Session session = this.sessionFactory.getCurrentSession();
            List<PersonResponse> list = session.createQuery("from Person p left join p.jobId").list();
        }
    }
    
    - PersonResponse
        - POJO with Person parameteres/variables without annotations and job name.
    

Advertisement

Answer

To be able to use left join in hql you should correct your mapping for Person in the following way:

@Entity
@Table(name = "person")
public class Person
{
   @ManyToOne
   @JoinColumn(name = "job_id")
   Job job;

   // ...
}

and then you will be able to write hql query like this:

List<Person> list = session.createQuery("select p from Person p left join p.job").list();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement