【问题标题】:JPA query without on没有打开的 JPA 查询
【发布时间】:2014-06-13 19:30:44
【问题描述】:

我尝试在 jpa 中转换此查询 我的 sql 原生查询。

SELECT *
FROM  tripinfo ti
inner join car c on ti.carid = c.id
left join customerdetail cd on ti.customerid = cd.id
left join station s on ti.fromstxid = s.id
where ti.starttime is null or ti.stoptime is null

我的 jpa 查询

SELECT ti
FROM TripInfo ti
join ti.car
left join CustomerDetail cd on ti.customer.customerDetail.id = cd.id
left join Station st on ti.fromstxid = st.id

jpa 2.0 中似乎不存在 on 命令。

TripInfo 类

public class tripInfo{
 Long id

 @OneToOne  
 JoinColumn(name = "customerId") //can be null 
 Customer customer;  

 @OneToOne
 @JoinColumn(name = "carid")  
 Car car;

 @Column(name = "tostxid")  //can be null
 Long toStxId;

 @Column(name = "fromstxid")  //can be null
 Long fromStxId;

 @OneToOne(cascade = { CascadeType.ALL })  
 @JoinColumn(name = "fromdp")  
 DP fromDP;

}

客户类别

public class Customer {
  Long id  
  @OneToOne(cascade = { CascadeType.ALL })  
  @JoinColumn(name = "customerDetail_customerid")  
  CustomerDetail customerDetail;
}

DP类

public class DP {
  @OneToOne(cascade = { CascadeType.ALL })
  @JoinColumn(name = "stationFrom")
  Station stationFrom;
}

有什么办法绕过 on 命令吗?

【问题讨论】:

    标签: mysql sql jpa-2.0


    【解决方案1】:

    在 JPA 查询中不允许连接的显式“打开”,而是由实体中定义的关系定义。在您获取客户详细信息的示例中,您可以执行如下所示的操作。

    SELECT ti
    join ti.car
    FROM TripInfo ti
    left join ti.customer.customerDetail
    

    但是,我没有看到为站类定义的任何关系。如果你有Station Class,那么,

     @Column(name = "fromstxid")  //can be null
     Long fromStxId;
    

    应该是,

    @Column(name = "fromstxid")
    @JoinColumn(name = "id") //Id in Station
    Station station;
    

    JPA 查询将是,

    SELECT ti
    join ti.car
    FROM TripInfo ti
    left join ti.customer.customerDetail
    left join ti.station
    

    希望这会有所帮助!

    【讨论】:

    • 我添加了它通过另一个类传递的引用
    • SELECT ti FROM TripInfo ti join ti.car tc left join ti.customer.customerDetail cd left join ti.fromDP.stationFrom st
    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2015-03-18
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多