【问题标题】:Joining two table entities with @OneToOne annotation generate "cross join" while "inner join" expected使用 @OneToOne 注释连接两个表实体会生成“交叉连接”,而需要“内部连接”
【发布时间】:2017-10-07 22:03:57
【问题描述】:

我有 OneToOne 表/实体 Person 和 Employee: 每个员工只有一个人,每个人都隶属于一个且只有一个员工。 生成的查询使用“cross join”关键字进行表连接,而“inner join”会更合适

@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=?
;

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 2013-02-25
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      相关资源
      最近更新 更多