简体   繁体   中英

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

Hi I am new for JPA & Criteria API. I am trying to fetch distinct values of a single column (trying to get only distinct values of TestId).I have below table in my DB.

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

I have below classes Model 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
}

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

I am getting below error.

Partial object queries are not allowed to maintain the cache or edited. You must use dontMaintainCache().

请尝试这里提到的这个选项((org.eclipse.persistence.jpa.JpaQuery)query).getDatabaseQuery().dontMaintainCache();

Result is not a list of Test but String , private String testId;

Changing

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

to

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

and the rest of code correspondingly might help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM