hibernate自定义多字段选择

时间:2017-02-05 22:09:15

标签: java spring hibernate hql

我们有几个模型如下。

@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Person {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int id;

    @Column(nullable = false, columnDefinition = "text")
    public String name;

    @Column(nullable = false, unique = true)
    public long ssid;

    @Column(nullable = false)
    public int age;

    @Column(nullable = false)
    public long registration;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "person")
    @Cascade(CascadeType.ALL)
    public List<Car> cars;


}

汽车模型

@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Car {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int id;

    @Column(nullable = false, columnDefinition = "text")
    private String name;

    @Column(nullable = false,  unique = true)
    public String plateNumber;

    @ManyToOne(fetch = FetchType.LAZY)
    public Person person;

    @ManyToOne(fetch = FetchType.LAZY)
    public Fabric fabric;

}

面料模型

@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Fabric {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int id;


    @Column(nullable = false, columnDefinition = "text")
    public String name;


    @OneToMany(fetch = FetchType.LAZY, mappedBy = "fabric")
    @Cascade(CascadeType.ALL)
    public List<Car> cars;
}

问题是,我们在不同模块上仅使用模型的某些属性。当我们调用简单的类型属性时,可以正常查询类似的东西;

session.createQuery("select name, cars from Person order by registration desc ");

我们收到错误。有人可以帮忙吗?

   org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
        org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
        org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
        org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)

org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
    org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
    org.hibernate.loader.Loader.doQuery(Loader.java:932)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
    org.hibernate.loader.Loader.doList(Loader.java:2615)
    org.hibernate.loader.Loader.doList(Loader.java:2598)
    org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2430)
    org.hibernate.loader.Loader.list(Loader.java:2425)
    org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:370)
    org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    org.hibernate.internal.SessionImpl.list(SessionImpl.java:1481)
    org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1441)
    org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1410)
    org.hibernate.Query.getResultList(Query.java:427)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    com.sun.proxy.$Proxy88.getAllPostOverview(Unknown Source)
    jarvis.api.story.PostController.getAllPostOverviews(PostController.java:51)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)

3 个答案:

答案 0 :(得分:0)

不要将cars指定为查询中的字段。

尝试添加LEFT JOIN FETCH子句,将在单个查询中加载已加入的关联集合的Person实体:

SELECT p.name FROM Person p LEFT JOIN FETCH p.cars ORDER BY p.registration DESC

答案 1 :(得分:0)

JPA并不支持您所做的事情,至少不是通过您尝试采取的途径。但是如果你从Car的角度处理问题,你可以。

SELECT c, c.person.name FROM Car c ORDER BY c.person.registration DESC

如果您想自动将此结果集填充到值对象中,可以使用SELECT NEW语法,也可以使用JPA CriteriaBuilder#construct方法。

SELECT NEW MyValueObject( c, c.person.name )
FROM Car c 
ORDER BY c.person.registration DESC

然后,您可以将List<MyValueObject>与Java Stream API结合使用,并根据需要将结果分组到内存中,如果有必要的话。

只需了解您获得的结果集包含:

  • Car个实例
  • 包含String名称值的Person个实例。

<强>更新

要构建关联Car的地图,我可能会添加c.person.id作为另一个构造函数参数传递给MyValueObject,以防您遇到有这种情况的情况两个同名的人。

List<MyValueObject> queryResults = query.getResultList();
List<List<MyValueObject>> groupedResults = queryResults
  .stream()
  .collect( Collectors.groupingBy( MyValueObject::getPersonId ) )
  .values();

groupedResults中的每个条目都是与Car实例相关联的Person个实例的列表。

答案 2 :(得分:0)

你可以试试这个......

session.createQuery("Select ps.name from Person as ps JOIN FETCH ps.cars ORDER BY ps.registration DESC");