简体   繁体   中英

JPQL and outer join

I have this problem with this simple left join.

I have two tables: Employee and Department

Employee has a many-to-one association with Department:

public class Employee {
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_EMPLOYEE")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "SURNAME")
    private String surname;

    @ManyToOne()    
    private Department department;

And department:

@Entity
@Table(name = "DEPARTMENT")
@SequenceGenerator(name = "SEQ_DEPARTMENT", sequenceName = "SEQ_DEPARTMENT", allocationSize = 1)
public class Department {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_DEPARTMENT")
    private Long id;

    @Column(name = "NAME")
    private String name;

On db

SELECT * FROM EMPLOYEE;
ID      NAME    SURNAME     DEPARTMENT_ID  
1   Massimo Ugues   1
2   Mazi    Ugues   2

SELECT * FROM DEPARTMENT;
ID      ADDRESS     NAME  
1   Via Gaber   Le betulle

So there is one Employee that does not belong to any Department.

Now I need to load the Employee that has id 2, the one with a departmentId = 2 that is not present on Db.

So this is the JPQL query:

select e, department from Employee e left outer join e.department department where e.name = :name and department.id = :id

And this is the relative sql generated:

SELECT t0.ID, t0.NAME, t0.SURNAME, t0.DEPARTMENT_ID, t1.ID, t1.ADDRESS, t1.NAME FROM {oj EMPLOYEE t0 LEFT OUTER JOIN DEPARTMENT t1 ON (t1.ID = t0.DEPARTMENT_ID)} WHERE ((t0.NAME = ?) AND (t1.ID = ?))
    bind => [Mazi, 2]

The problem is not in the join but in the t1.ID = ? . It should be t0.ID = ? where t0 is the employee table.

Any idea how to make it works?

Kind regards. Massimo

The problem is not Hibernate. The problem is your database. If an employee doesn't belong to any department, it should have NULL in the department_id column, and not some unexisting department ID. You should have a foreign key constraint on employee.department_id to make sure such incoherences never happen. That's the C in ACID.

So, my advice is: fix the data:

update employee set department_id = null where department_id not in (select id from department)

Also, note that doing a left join and forcing the department to have a specific ID is the same as doing an inner join.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM