如何在 Criteria API(JPA) 中获取单个列的不同值

How to get distinct values of a single column in Criteria API(JPA)

嗨,我是 JPA 和标准的新手 API。 我正在尝试获取单个列的不同值(试图仅获取 TestId 的不同值)。我的数据库中有以下 table。

__________________________________
|TestId(Pk) | TestCol(PK) | TestEx|
__________________________________

我有以下 classes 型号 Class

@Data
@Entity
@Table(schema = "TEST", name = "TEST_TYPE")
public class Test {
    @EmbeddedId
    private TestPK id;

    @Column(nmae = "TestEX")
    private double testEx
}

@Data
@Embeddable
public class TestPK {
    @Column(name = "TestId")
    private String testId;

    @Column(name="TestCol")
    private String testcol
}

存储库class

public class TestRepoImpl {

    @PersistenceContext
    EntityManager em;

    @Override
    public List<Test> getData() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Test> cq = cb.createQuery(Test.class);
        Root<Test> root = cq.from(Test.class);

        // cq.get(Test_.id).get(TestPK_.testId);
        // cq.select(root);
        cq.multiselect(root.get(Test_.id).get(TestPK_.testId));
        cq.distinct(true);
        // List<Tuple> ts = em.createQuery(cq).getResultList();
        List<Test> data = em.createQuery(cq).getResultList();
        return data;
    }
} 

我遇到了以下错误。

部分对象查询不允许维护缓存或编辑。 您必须使用 dontMaintainCache()。

请按照 ((org.eclipse.persistence.jpa.JpaQuery)query).getDatabaseQuery().dontMaintainCache();

中所述尝试此选项

结果不是 Test 的列表,而是 Stringprivate String testId;

改变

CriteriaQuery<Test> cq = cb.createQuery(Test.class);

CriteriaQuery<String> cq = cb.createQuery(String.class);

以及相应的其余代码可能会有所帮助。