JPA左外连接与Group缺少大小为零的集合项

时间:2016-02-22 17:12:28

标签: java hibernate jpa spring-boot

我试图在2个相关实体上执行简单的左外连接。

以下是实体(省略的getter / setters)

@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子句的情况下运行本机查询,则返回正确的结果。

1 个答案:

答案 0 :(得分:2)

您的查询在部件关系中有2个不同的连接:

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

第一个是在选择范围内,&#34;尺寸(c.parts)&#34;迫使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"