如何使用Hibernate保存或检索数组列

时间:2014-03-26 01:47:29

标签: java hibernate postgresql

我使用Postgres,我有一列ufsinss character(2)[],如array。我创建了userType模型以供使用,因为我在google中找到了一些帖子,指出了处理此问题的方法,因为Hibernate没有本地方法来处理它。

我的userType有两个代码。

public static final String TYPE = "arrayStringType";

    public Class<String[]> returnedClass() {
        return String[].class;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImpl, Object obj) throws HibernateException, SQLException {

        Array array = rs.getArray(names[0]);
        return NullUtil.isNull(array) ? null : (String[]) array.getArray(); 
   }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor sessionImpl) throws HibernateException, SQLException {

        Connection connection = st.getConnection();
        String[] stringArray = (String[]) value;
        Array array = connection.createArrayOf("character", stringArray);
        st.setArray(index, array);      
    }

我的模型实体声明如下:

@Type(type = ArrayStringType.TYPE)
private String[] ufsInss;

但我收到了错误:

Mar 25, 2014 10:33:27 PM org.apache.catalina.core.StandardWrapperValve invoke
Grave: Servlet.service() for servlet [Faces Servlet] in context with path [/ecred2_manat] threw exception
java.lang.reflect.UndeclaredThrowableException
    at com.sun.proxy.$Proxy79.flush(Unknown Source)
    at com.paradigma.ecred.view.filter.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:38)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    ... [snip] ...
    ... 51 more
Caused by: java.lang.AbstractMethodError: org.postgresql.jdbc3g.Jdbc3gConnection.createArrayOf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/sql/Array;
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.continueInvocation(ConnectionProxyHandler.java:138)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy80.createArrayOf(Unknown Source)
    at com.paradigma.ecred.dao.hibernate.type.ArrayStringType.nullSafeSet(ArrayStringType.java:34)
    at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:158)
    ... [snip] ...
    ... 56 more
  

编辑1

将我的JDBC版本更改为postgresql-9.3-1101.jdbc41.jar后,当我尝试从Criteria执行Hibernate语句时,我收到此错误。

org.hibernate.exception.SQLGrammarException: Não foi possível encontrar tipo matriz para nome fornecido character.
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.continueInvocation(ConnectionProxyHandler.java:146)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy80.createArrayOf(Unknown Source)
    at com.paradigma.ecred.dao.hibernate.type.ArrayStringType.nullSafeSet(ArrayStringType.java:34)
    at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:158)
 ... [snip] 
Caused by: org.postgresql.util.PSQLException: Não foi possível encontrar tipo matriz para nome fornecido character.
    at org.postgresql.jdbc4.AbstractJdbc4Connection.createArrayOf(AbstractJdbc4Connection.java:83)
    at org.postgresql.jdbc4.Jdbc4Connection.createArrayOf(Jdbc4Connection.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.continueInvocation(ConnectionProxyHandler.java:138)
    ... 100 more
  

编辑3

更新我的代码后

@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor sessionImpl) throws HibernateException, SQLException {

    Connection connection = st.getConnection();
    String[] stringArray = (String[]) value;

    if (NullUtil.isNull(stringArray)) {
        st.setNull(index, IntegerType.INSTANCE.sqlType());          
    } else {            
        Array array = connection.createArrayOf("varchar", stringArray);
        st.setArray(index, array);      
    }

}

我收到了新错误

Mar 26, 2014 6:46:44 AM com.sun.faces.context.ExceptionHandlerImpl throwIt
Informações: Exception when handling error trying to reset the response.
org.hibernate.exception.GenericJDBCException: ERRO: transação atual foi interrompida, comandos ignorados até o fim do bloco de transação
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy81.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3185)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3087)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3416)
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:276)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
    at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:62)
    at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1614)
    at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
    at com.paradigma.ecred.dao.impl.HibernateDAOImpl.findByFilter(HibernateDAOImpl.java:118)
    at com.paradigma.ecred.dao.impl.HibernateDAOImpl.findByFilter(HibernateDAOImpl.java:1)
    at com.paradigma.ecred.service.impl.ServiceImpl.findByFilter(ServiceImpl.java:96)
    at com.paradigma.ecred.service.impl.PropostaServiceImpl.findByFilter(PropostaServiceImpl.java:1111)
    at com.paradigma.ecred.view.LazyPojoDataModel.load(LazyPojoDataModel.java:70)
    at org.primefaces.component.datatable.DataTable.loadLazyData(DataTable.java:737)
    at org.primefaces.component.datatable.DataTableRenderer.preEncode(DataTableRenderer.java:93)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:81)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1903)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:889)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1896)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1899)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1899)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:451)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.paradigma.ecred.view.filter.NoCacheFilter.doFilter(NoCacheFilter.java:36)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.paradigma.ecred.view.filter.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:34)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.paradigma.ecred.view.filter.IE8CompatibilityFixFilter.doFilter(IE8CompatibilityFixFilter.java:23)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:64)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)

上面有更多的线路错误但是SO限制。

2 个答案:

答案 0 :(得分:2)

你有两个问题:

  • 您使用的是JDBC3驱动程序;以及

  • 您在character电话中使用了无效的类型名称createArrayOf。您必须使用与表的定义方式相匹配的有效SQL类型,例如varchartext

尝试:

Array array = connection.createArrayOf("text", stringArray);

(根据您在数据库中声明数组的方式进行调整)。

答案 1 :(得分:0)

首先需要更新你的驱动器,因为你的错误是缺少一个类。稍后您创建一个要转换的类......

在您的情况下,您需要按照我的建议制作您的方法。

NullSafeGet将是这样的

Array array = rs.getArray(names[0]);        
    return NullUtil.isNull(array) ? null : (String[]) array.getArray();

使用此方法,您可以检索列的类型,正如我所说的那样。但是您需要在列中手动插入数据以恢复并使用此代码。

String columnType = array.getBaseTypeName();

所以它会返回bpchar

您将实施方法nullSafeSet

Connection connection = st.getConnection();
String[] stringArray = (String[]) value;

if (NullUtil.isNull(stringArray)) {
    st.setNull(index, Types.ARRAY);
} else {            
    Array array = connection.createArrayOf("bpchar", stringArray);
    st.setArray(index, array);      
}

您可以使用它来制作其他数组类型,但需要使用它来获取列的类型。