5

I need to select companies from the database with their active addresses (address.address_status_id = 1). If the address is inactive the address columns should contain nulls.

The following query does exactly what I want:

select c.id, c.name, a.id, a.street
from company c
left join 
(select * from address where address_status_id = 1) a 
on c.id = a.company_id

I tried this in Java/QueryDSL:

JPAQuery query = new JPAQuery(entityManager);
query = query.from(qCompany);
query = query.leftJoin(company.addresses, new JPASubQuery().from(qAddress)    
.where(qAddress.addressStatusId.eq(AddressStatuss.ACTIVE.asBigDecimal())).list(qAddress));

However JPA (and consequently the JPAQuery in QueryDSL) doesn't support a subquery in a JOIN clause

Is there a way to rephrase the SQL statement so that it can be expressed in JPA/QueryDSL?

edit: We're using Oracle DB and Hibernate JPA provider if it makes a difference.

4

2 回答 2

6

也许像这样

select c.id, c.name, a.id, a.street
from Company c
left join c.addresses a on a.addressStatusId = 1

并在 Querydsl

query.from(c)
     .leftJoin(c.addresses, a)
     .on(a.addressStatusId.eq(1))
     .list(c.id, c.name, a.id, a.street)
于 2013-07-10T12:27:22.277 回答
1

我会使用 Oracle DB JDBC。你可以在这里得到。

根据您尝试构建 Applet 还是应用程序,您必须在 JDBC 的小版本和 OCI 版本之间进行选择。更多信息请点击此处

我将假设您正在构建一个应用程序,因此我将在此示例中使用 OCI。

Class.forName("oracle.jdbc.OracleDriver");
Connection con = null;
Statement stmt = null;
ResultSet rset = null;
try{
    con = DriverManager.getConnection("jdbc:oracle:oci:@//192.168.1.100", "user", "password");

    stmt = con.prepareStatement();

    rset = stmt.executeQuery("SELECT name, address, phonenumber FROM tbl_comanies");

    while(rset.next()){
        String name = rset.getString(1);
        String address = rset.getString(2);
        int phonenumber = rset.getInt(3);
        //The number passed to the get...()-Method is the place in the SQL query. (Here, name=1, address=2, phonenumber=3)
    }
} catch (SQLException ex) {
    System.out.println(ex.getMessage());
} finally {
    try {
        if(rset != null)
            rset.close();
        if(stmt != null)
            stmt.close();
        if(con != null)
            con.close();
    }
}

希望这可以帮助你。

问候,安迪

于 2013-07-10T08:53:56.553 回答