使用@OneToOne注释连接两个表实体生成"交叉连接"而"内部联接"预期

时间:2017-05-09 14:23:20

标签: spring-data-jpa one-to-one cross-join

我有OneToOne表/实体Person和Employee: 每个员工只有一个人,每个人只有一个员工。 生成的查询执行表连接"交叉连接"关键字while"内部联接"会更合适

@Entity
@Table(name="person")
@Data
public class Person implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_Person", unique=true, nullable=false)
    private long id;

    @Column(nullable=false, length=50)
    private String name;

    @Column(nullable=false, length=255)
    private String EMail;
}

@Entity
@Table(name="employee")
@Data
public class Employee implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_Employee", unique=true, nullable=false)
    private long id;

    @Column(nullable=false, length=50)
    private String numero;

    @OneToOne(fetch = FetchType.EAGER, optional=false)
    @JoinColumn(name="id_Employee")
    private Person person;
}

存储库:

public interface EmployeeRepository extends CrudRepository { @Query("SELECT e FROM Employee e WHERE LOWER(e.person.name) LIKE CONCAT(LOWER(:name),'%')") List findByName(@Param("name") String name); }

以下是生成的查询:

select employee0_.id_Employee as id_Emplo1_0_, employee0_.department as departme2_0_ 
from employee employee0_ 
cross join person person1_ 
where employee0_.id_Employee=person1_.id_Person 
and (lower(person1_.name) like concat(lower(?), '%'))
;
select person0_.id_Person as id_Perso1_2_0_, person0_.EMail as EMail2_2_0_, person0_.name as name3_2_0_ 
from person person0_ 
where person0_.id_Person=?
;

1 个答案:

答案 0 :(得分:0)

您在实体Employee中有错误,加入列应为 id_Person 。 除此之外,我建议使用Querydsl对您的连接进行细粒度控制。您的查询将如下所示:

query.from(employee).leftJoin(employee.person, person)
.where(person.name.lower().like(name.toLowerCase() + "%")).fetch();