Hibernate tuple criteria queries

£可爱£侵袭症+ 提交于 2019-12-12 00:50:20

问题


I am trying to create a query using hibernate following the example given in section 9.2 of chapter 9

The difference with my attempt is I am using spring MVC 3.0. Here is my Address class along with the method i created.

@RooJavaBean
@RooToString
@RooEntity
@RooJson
public class Address {

    @NotNull
    @Size(min = 1)
    private String street1;

    @Size(max = 100)
    private String street2;

    private String postalcode;

    private String zipcode;

    @NotNull
    @ManyToOne
    private City city;

    @NotNull
    @ManyToOne
    private Country country;

    @ManyToOne
    private AddressType addressType;

    @Transient
    public static List<Tuple> jqgridAddresses(Long pID){
        CriteriaBuilder builder = Address.entityManager().getCriteriaBuilder();
        CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
        Root<Address> addressRoot = criteria.from( Address.class );
        criteria.multiselect(addressRoot.get("id"), addressRoot.get("street1"), addressRoot.get("street2"));
        criteria.where(builder.equal(addressRoot.<Set<Long>>get("id"), pID));
        return Address.entityManager().createQuery( criteria ).getResultList();
    }
}

The method called jqgridAddresses above is the focus. I opted not to use the "Path" because when I say something like Path idPath = addressRoot.get( Address_.id ); as in section 9.2 of the documentation, the PathAddress_.id stuff produces a compilation error.

The method above returns an empty list of type Tuple as its size is zero even when it should contain something. This suggests that the query failed. Can someone please advise me.


回答1:


OK so i made some minor adjustments to my logic which is specific to my project, however, the following approach worked perfectly. Hope it hepls someone in need !

@Transient
public static List<Tuple> jqgridPersons(Boolean isStudent, String column, String orderType, int limitStart, int limitAmount){
    CriteriaBuilder builder = Person.entityManager().getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
    Root<Person> personRoot = criteria.from(Person.class );
    criteria.select(builder.tuple(personRoot.get("id"), personRoot.get("firstName"), personRoot.get("lastName"), personRoot.get("dateOfBirth"), personRoot.get("gender"), personRoot.get("maritalStatus"))); 
    criteria.where(builder.equal( personRoot.get("isStudent"), true));
    if(orderType.equals("desc")){
        criteria.orderBy(builder.desc(personRoot.get(column)));
    }else{
        criteria.orderBy(builder.asc(personRoot.get(column)));
    }
    return Address.entityManager().createQuery( criteria ).setFirstResult(limitStart).setMaxResults(limitAmount).getResultList(); 
}


来源:https://stackoverflow.com/questions/10554039/hibernate-tuple-criteria-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!