簡體   English   中英

JPA通過缺少零大小的集合項而與Group左外部聯接

[英]JPA Left outer join with Group by missing collection item with zero size

我正在嘗試對2個相關實體執行簡單的左外部聯接。

以下是實體(省略的getter / setter)

@Entity
public class TestPart {
    @Id
    @GeneratedValue
    private int partId;

    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="f_categoryId", nullable=false)
    private TestCategory category;
}

@Entity
public class TestCategory {
    @Id
    @GeneratedValue
    private int categoryId;

    @OneToMany(mappedBy="category", cascade={CascadeType.ALL})
    private Set<TestPart> parts = new HashSet<>();
}

TestPart是關系的擁有方。

現在,我需要獲取每個TestCategory的TestPart計數。 因此,我使用以下JPQL查詢。

select distinct c, size(c.parts) from TestCategory c left join c.parts group by c

我希望在TestPart中沒有條目的類別將返回計數0,但這不會發生。 以上查詢僅返回在TestPart中至少具有一個條目的類別的計數。

我正在使用以下配置。

 1. spring-boot
 2. spring-data
 3. hibernate (as loaded by spring-data)
 4. Postgres 9.5

以下是測試的來源。

的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>TestLeftOuterJoin</groupId>
    <artifactId>TestLeftOuterJoin</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss.SSS zzz

spring.jpa.database=POSTGRESQL
spring.datasource.platform=postgres
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.driver=org.postgresql.Driver
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.url = jdbc:postgresql://localhost:5432/test?sslmode=disable
spring.datasource.username = postgres
spring.datasource.password = test


#spring.jpa.database=H2
#spring.datasource.platform=H2
#spring.jpa.show-sql=true
#spring.jpa.hibernate.ddl-auto=update
#spring.datasource.driver=org.h2.Driver
#hibernate.dialect=org.hibernate.dialect.H2Dialect
#spring.datasource.url = jdbc:h2:mem:testdb
#spring.datasource.username = sa
#spring.datasource.password =

TestPart

package test.entity;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class TestPart {
    @Id
    @GeneratedValue
    private int partId;

    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="f_categoryId", nullable=false)
    private TestCategory category;

    public int getPartId() {
        return partId;
    }

    public void setPartId(int partId) {
        this.partId = partId;
    }

    public TestCategory getCategory() {
        return category;
    }

    public void setCategory(TestCategory category) {
        this.category = category;
    }
}

TestCategory

package test.entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class TestCategory {

    @Id
    @GeneratedValue
    private int categoryId;

    @OneToMany(mappedBy="category", cascade={CascadeType.ALL})
    /*@ElementCollection(fetch=FetchType.EAGER)*/
    private Set<TestPart> parts = new HashSet<>();

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public Set<TestPart> getParts() {
        return parts;
    }

    public void setParts(Set<TestPart> parts) {
        this.parts = parts;
    }
}

PartRepository

package test.entity;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PartRepository extends PagingAndSortingRepository<TestPart, Long>{

}

CategoryRepository

package test.entity;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CategoryRepository extends PagingAndSortingRepository<TestCategory, Long>{

}

應用

package test;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration
public class ApplicationConfig {

}

JunitTest

package test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;

import test.entity.CategoryRepository;
import test.entity.PartRepository;
import test.entity.TestCategory;
import test.entity.TestPart;
import test.queryresult.TestQueryResult;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(ApplicationConfig.class)
public class JunitTest {

    @PersistenceContext
    EntityManager entityManager;

    @Autowired
    private CategoryRepository categoryRepo;

    @Autowired
    private PartRepository partRepositry;

    @Before
    public void init() {
        /*
         * adding 2 categories, category1 and category2.
         * adding 3 parts part1, part2 and part3
         * all parts are associated with category2
         */
        TestCategory category1 = new TestCategory();
        categoryRepo.save(category1);

        TestCategory category2 = new TestCategory();

        TestPart part1 = new TestPart();
        part1.setCategory(category2);

        TestPart part2 = new TestPart();
        part2.setCategory(category2);

        TestPart part3 = new TestPart();
        part3.setCategory(category2);

        Set<TestPart> partSet = new HashSet<>();
        partSet.addAll(Arrays.asList(part1, part2, part3));

        partRepositry.save(partSet);

    }

    @Test
    public void test() {
        System.out.println("##################### started " + TestQueryResult.class.getName());

        String query = "select distinct c, size(c.parts) from TestCategory c left join c.parts group by c";
        List list = entityManager.createQuery(query).getResultList();
        System.out.println("################# size " + list.size());

        Assert.isTrue(list.size() == 2, "list size must be 2");
    }
}

編輯

添加由JPQL生成的查詢,

SELECT DISTINCT testcatego0_.category_id     AS col_0_0_, 
                Count(parts2_.f_category_id) AS col_1_0_, 
                testcatego0_.category_id     AS category1_0_ 
FROM   test_category testcatego0_ 
       LEFT OUTER JOIN test_part parts1_ 
                    ON testcatego0_.category_id = parts1_.f_category_id, 
       test_part parts2_ 
WHERE  testcatego0_.category_id = parts2_.f_category_id 
GROUP  BY testcatego0_.category_id

可以看出,JPQL正在產生不必要的where子句testcatego0_.category_id = parts2_.f_category_id ,這引起了問題。

如果運行不帶where子句的本機查詢,它將返回正確的結果。

您的查詢在部件關系中具有2個不同的聯接:

"select distinct c, size(c.parts) from TestCategory c left join c.parts group by c"

第一個是在select中,“ size(c.parts)”強制JPA遍歷關系,我猜想這可能是導致生成的SQL中內部聯接的原因,盡管這可能是提供程序錯誤,因為我沒有看到您將如何獲得規格要求的0大小-應該使用某種子查詢來獲取值,而不只是計數。

第二個是from子句中的顯式左連接。 即使未在任何地方使用它,您也需要查詢才能將其包括在SQL中。

相反,您可能想要的是:

"select distinct c, size(c.parts) from TestCategory c"

哪個應該按照規范工作,否則,請嘗試

"select distinct c, count(part.id) from TestCategory c left join c.parts part group by c"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM