gpt4 book ai didi

java - JPA 通过缺少大小为零的集合项与 Group 进行左外连接

转载 作者:行者123 更新时间:2023-11-30 03:02:42 24 4
gpt4 key购买 nike

我正在尝试对 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 =

测试部分

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;
}
}

测试类别

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;
}
}

零件存储库

package test.entity;

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

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

}

类别存储库

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 子句的情况下运行 native 查询,它将返回正确的结果。

最佳答案

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

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

第一个是在选择中,“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"

关于java - JPA 通过缺少大小为零的集合项与 Group 进行左外连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35559711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com