Java Hibernate条件查询以获取特定列

Java Hibernate条件查询以获取特定列,java,mysql,hibernate,hibernate-criteria,Java,Mysql,Hibernate,Hibernate Criteria,我正在代码中使用条件查询。它总是从…select*from… 相反,我希望忽略查询中的一列(字段),因为该字段有大量以字节形式存储的数据。这会导致性能问题 有人能给出一个想法吗 一些更新 我在我的查询中添加了一个投影,它创建了一个类似于 select this_.TEMPLATE_ID as y0_, this_.TEMPLATE_NAME as y1_, this_.CREATE_DATE as y2_, this_.UPDATE_DATE as y3_,

我正在代码中使用条件查询。它总是从…
select*from…

相反,我希望忽略查询中的一列(字段),因为该字段有大量以字节形式存储的数据。这会导致性能问题

有人能给出一个想法吗


一些更新

我在我的查询中添加了一个投影,它创建了一个类似于

select
    this_.TEMPLATE_ID as y0_,
    this_.TEMPLATE_NAME as y1_,
    this_.CREATE_DATE as y2_,
    this_.UPDATE_DATE as y3_,
    this_.STATUS_CODE as y4_,
    this_.USER_ID as y5_,
    this_.UPDATED_BY as y6_,
    this_.CATEGORY_ID as y7_,
    this_.PRACTICE_ID as y8_ 
from
    templates this_ 
inner join
    user user1_ 
        on this_.USER_ID=user1_.USER_ID 
inner join
    template_categories category2_ 
        on this_.CATEGORY_ID=category2_.CATEGORY_ID 
where
    y4_=? 
    and y8_=? 
    and y5_ in (
        ?, ?
    ) 
order by
    y1_ asc limit ?
现在的问题是<代码>where子句中的未知列“y4” 对于y8,y5,同样的误差意味着对于所有闭合的地方,它给出了一个误差

我把它改成了像

select
    this_.TEMPLATE_ID as y0_,
    this_.TEMPLATE_NAME as y1_,
    this_.CREATE_DATE as y2_,
    this_.UPDATE_DATE as y3_,
    this_.STATUS_CODE as y4_,
    this_.USER_ID as y5_,
    this_.UPDATED_BY as y6_,
    this_.CATEGORY_ID as y7_,
    this_.PRACTICE_ID as y8_ 
from
    templates this_ 
inner join
    user user1_ 
        on this_.USER_ID=user1_.USER_ID 
inner join
    template_categories category2_ 
        on this_.CATEGORY_ID=category2_.CATEGORY_ID 
where
    this_.STATUS_CODE=1
    and this_.PRACTICE_ID=1 
    and this_.USER_ID in (
        1, 2
    ) 
order by
    y1_ asc limit ?

它成功了。但是我不知道如何在HQL中修改它?

您可以基于这个类映射另一个实体(您应该使用实体名称来区分这两个实体),第二个实体将是dto(别忘了这一点)。 您应该将第二个定义为readonly,并给它起一个好名字,以便清楚这不是一个常规实体。 顺便说一句,只选择几个列称为投影,所以谷歌使用它会更容易

备选方案-您可以使用所需字段列表创建命名查询(将它们放入“选择”中),或使用带投影的条件指定要返回的列

示例

SQL查询

冬眠替代方案

Criteria cr=session.createCriteria(User.class)
.setProjection(Projections.projectionList()项目)
.add(Projections.property(“id”),“id”)
.add(Projections.property(“名称”),“名称”))
.setResultTransformer(Transformers.aliasToBean(User.class));
List=cr.List();

您可以将JPQL和JPA标准API用于任何类型的DTO投影(仅将选定列映射到DTO类)。请看下面的代码片段,其中显示了如何有选择地选择不同的列,而不是 选择所有列。这些示例还显示了如何从中选择各种列 连接多个列。我希望这有帮助

JPQL代码:

String dtoProjection = "new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto"
                + "(i.id, i.name, i.fatherName, i.address, id.proofNo, "
                + " v.vehicleNumber, v.vechicleType, s.name, s.fatherName, "
                + " si.name, sv.vehicleNumber , svd.name) ";

        List<InstructorDto> instructors = queryExecutor.fetchListForJpqlQuery(
                "select " + dtoProjection + " from Instructor i " + " join i.idProof id " + " join i.vehicles v "
                        + " join i.students s " + " join s.instructors si " + " join s.vehicles sv "
                        + " join sv.documents svd " + " where i.id > :id and svd.name in (:names) "
                        + " order by i.id , id.proofNo , v.vehicleNumber , si.name , sv.vehicleNumber , svd.name ",
                CollectionUtils.mapOf("id", 2, "names", Arrays.asList("1", "2")), InstructorDto.class);

        if (Objects.nonNull(instructors))
            instructors.forEach(i -> i.setName("Latest Update"));

        DataPrinters.listDataPrinter.accept(instructors);
String dtoproject=“new com.katariasoft.technologies.jpaHibernate.college.data.dto.InstructorDto”
+(i.id,i.name,i.fatherName,i.address,id.no,)
+v.vehicleNumber,v.vechicleType,s.name,s.fatherName
+“si.name,sv.vehicleNumber,svd.name)”;
List instructors=queryExecutor.fetchListForJpqlQuery(
“从讲师i”+“加入i.idProof id”+“加入i.v”中选择“+dtoProjection+”
+“加入i.学生s”+“加入s.讲师s”+“加入s.车辆sv”
+在(:名称)中加入sv.documents svd“+”其中i.id>:id和svd.name
+“按识别号、识别号、v.vehicleNumber、si.name、sv.vehicleNumber、svd.name订购”,
CollectionUtils.mapOf(“id”,2,“name”,Arrays.asList(“1”,“2”)),InstructorDto.class);
if(Objects.nonNull(讲师))
forEach(i->i.setName(“最新更新”);
DataPrinters.listDataPrinter.accept(讲师);
JPA标准API代码:

@Test
    public void fetchFullDataWithCriteria() {
        CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
        CriteriaQuery<InstructorDto> cq = cb.createQuery(InstructorDto.class);

        // prepare from expressions
        Root<Instructor> root = cq.from(Instructor.class);
        Join<Instructor, IdProof> insIdProofJoin = root.join(Instructor_.idProof);
        Join<Instructor, Vehicle> insVehicleJoin = root.join(Instructor_.vehicles);
        Join<Instructor, Student> insStudentJoin = root.join(Instructor_.students);
        Join<Student, Instructor> studentInsJoin = insStudentJoin.join(Student_.instructors);
        Join<Student, Vehicle> studentVehicleJoin = insStudentJoin.join(Student_.vehicles);
        Join<Vehicle, Document> vehicleDocumentJoin = studentVehicleJoin.join(Vehicle_.documents);

        // prepare select expressions.
        CompoundSelection<InstructorDto> selection = cb.construct(InstructorDto.class, root.get(Instructor_.id),
                root.get(Instructor_.name), root.get(Instructor_.fatherName), root.get(Instructor_.address),
                insIdProofJoin.get(IdProof_.proofNo), insVehicleJoin.get(Vehicle_.vehicleNumber),
                insVehicleJoin.get(Vehicle_.vechicleType), insStudentJoin.get(Student_.name),
                insStudentJoin.get(Student_.fatherName), studentInsJoin.get(Instructor_.name),
                studentVehicleJoin.get(Vehicle_.vehicleNumber), vehicleDocumentJoin.get(Document_.name));

        // prepare where expressions.
        Predicate instructorIdGreaterThan = cb.greaterThan(root.get(Instructor_.id), 2);
        Predicate documentNameIn = cb.in(vehicleDocumentJoin.get(Document_.name)).value("1").value("2");
        Predicate where = cb.and(instructorIdGreaterThan, documentNameIn);

        // prepare orderBy expressions.
        List<Order> orderBy = Arrays.asList(cb.asc(root.get(Instructor_.id)),
                cb.asc(insIdProofJoin.get(IdProof_.proofNo)), cb.asc(insVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(studentInsJoin.get(Instructor_.name)), cb.asc(studentVehicleJoin.get(Vehicle_.vehicleNumber)),
                cb.asc(vehicleDocumentJoin.get(Document_.name)));

        // prepare query
        cq.select(selection).where(where).orderBy(orderBy);
        DataPrinters.listDataPrinter.accept(queryExecutor.fetchListForCriteriaQuery(cq));

    }
@测试
public void fetchFullDataWithCriteria(){
CriteriaBuilder cb=criteriaUtils.CriteriaBuilder();
CriteriaQuery cq=cb.createQuery(InstructorDto.class);
//从表达中准备
Root Root=cq.from(讲师级);
Join-insideproof-Join=root.Join(讲师\ idProof);
Join insVehicleJoin=根连接(讲师车辆);
Join insStudentJoin=root.Join(讲师学生);
Join StudentInJoin=insStudentJoin.Join(学生导师);
Join studentVehicleJoin=insStudentJoin.Join(学生车辆);
Join vehicleDocumentJoin=studentVehicleJoin.Join(车辆文档);
//准备选择表达式。
CompoundSelection=cb.construct(InstructorDto.class,root.get(Instructor.id),
root.get(讲师姓名)、root.get(讲师父亲姓名)、root.get(讲师地址),
Inside proof join.get(IdProof\uuu.proof No),insVehicleJoin.get(Vehicle\uu.vehicleNumber),
insVehicleJoin.get(车辆向量类型),insStudentJoin.get(学生姓名),
insStudentJoin.get(学生父亲姓名),studentInsJoin.get(教师姓名),
studentVehicleJoin.get(车辆号)、vehicleDocumentJoin.get(文件名));
//准备好你的表达方式。
谓词instructorIdGreaterThan=cb.greaterThan(root.get(讲师id),2);
谓词documentNameIn=cb.in(vehicleDocumentJoin.get(Document.name)).value(“1”).value(“2”);
谓词where=cb.and(instructorIdGreaterThan,documentNameIn);
//准备orderBy表达式。
List orderBy=Arrays.asList(cb.asc(root.get(讲师\讲师id)),
cb.asc(InsideProofJoin.get(IdDroop\uU.proofNo)),cb.asc(insVehicleJoin.get(Vehicle\uU.vehicleNumber)),
cb.asc(studentInsJoin.get(讲师姓名)),cb.asc(studentVehicleJoin.get(车辆编号)),
cb.asc(车辆文档join.get(文档名称));
//准备查询
cq.select(selection).where(where).orderBy(orderBy);
accept(queryExecutor.fetchListForCriteriaQuery(cq));
}

我喜欢这种方法,因为它简单明了:

    String getCompaniesIdAndName = " select "
            + " c.id as id, "
            + " c.name as name "
            + " from Company c ";

    @Query(value = getCompaniesWithoutAccount)
    Set<CompanyIdAndName> findAllIdAndName();

    public static interface CompanyIdAndName extends DTO {
        Integer getId();

        String getName();

    }
String getCompaniesIdAndName=“选择”
+“c.id作为id,”
+“c.名称作为名称”
+“来自c公司”;
@查询(值=GetCompanyWithoutAccount)
设置findAllIdAndName();
公共静态接口COMPANYANDNAME将DTO扩展到{
整数getId();
字符串getName();
}

您可以为此使用
多选功能

   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }
            
CriteriaBuilder cb=session.getCriteriaBuilder();
CriteriaQuery cquery=cb.createQuery(对象[].cl
    String getCompaniesIdAndName = " select "
            + " c.id as id, "
            + " c.name as name "
            + " from Company c ";

    @Query(value = getCompaniesWithoutAccount)
    Set<CompanyIdAndName> findAllIdAndName();

    public static interface CompanyIdAndName extends DTO {
        Integer getId();

        String getName();

    }
   CriteriaBuilder cb=session.getCriteriaBuilder();
            CriteriaQuery<Object[]> cquery=cb.createQuery(Object[].class);
            Root<Car> root=cquery.from(User.class);
            cquery.multiselect(root.get("id"),root.get("Name"));
            Query<Object[]> q=session.createQuery(cquery);
            List<Object[]> list=q.getResultList();
            System.out.println("id        Name");
            for (Object[] objects : list) {
                System.out.println(objects[0]+"        "+objects[1]);
             }