Error operator does not exist character varying bytea

Hibernate Community Forums

Hi, I’m trying to migrate from HSQLDB Default Datasource on JBoss 4.0.3rc1 to a Postgresql DB.

When using my app on HSQLDB, no problem. When trying to use pgSql Datasource, got this error:

java.sql.SQLException: ERROR: operator does not exist: character varying = bytea

(see exception stack trace)

You will see I’m using a UserEnumType (enhanced version posted in wiki) to persit an enum called ‘userGroup’.

To terminate, here is my query and ‘create table’ pg script:

// GroupEnum group;

list = (List<User>) em.createQuery(«from User where userGroup = :group»).setParameter(«group», group).getResultList();

CREATE TABLE users — GENERATED BY HIBERNATE

(

id int8 NOT NULL,

disabled bool NOT NULL,

«password» varchar(32),

username varchar(32),

firstconnection timestamp,

lastconnection timestamp,

usergroup varchar(20),

person_id int8,

CONSTRAINT users_pkey PRIMARY KEY (id),

CONSTRAINT fk4d495e8e149448b FOREIGN KEY (person_id) REFERENCES person (id) ON UPDATE NO ACTION ON DELETE NO ACTION,

CONSTRAINT users_username_key UNIQUE (username)

)

WITH OIDS;

Any idea?

Thx,

Renaud

—————-

Hibernate version: 3.1alpha [JBoss 4.0.3RC1 w/EJB3]

Mapping documents:

package be.sysmedit.model.core.app;

import java.io.Serializable;

import java.util.Date;

import java.util.HashSet;

import java.util.Set;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.GeneratorType;

import javax.persistence.Id;

import javax.persistence.ManyToMany;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

import javax.persistence.Transient;

import org.apache.commons.lang.builder.HashCodeBuilder;

import org.apache.commons.lang.builder.ToStringBuilder;

import org.hibernate.annotations.Parameter;

import org.hibernate.annotations.Type;

import org.hibernate.annotations.TypeDef;

import org.hibernate.annotations.TypeDefs;

import be.sysmedit.model.core.Person;

import be.sysmedit.model.itrequest.Request;

import be.sysmedit.persistence.types.EnumUserType;

/**

* Represents the application user.

*

* @todo Ajouter une spécialisation ItUser dans .model.itrequest et transférer

* watches

*/

@TypeDefs( {

@TypeDef(name = «group», typeClass = EnumUserType.class, parameters = {

@Parameter(name = «enumClassName», value = «be.sysmedit.model.core.app.GroupEnum»)

})

})

@Entity

// Needed by postgresql since it’s a reserved word and hibernate don’t care:

@Table (name = «USERS»)

public class User implements Serializable {

private Long id;

private String userName;

private String password;

private boolean disabled;

private Date firstConnection;

private Date lastConnection;

private GroupEnum userGroup;

public Person person;

public Set<Request> requestWatches = new HashSet<Request>();

public User() {

}

public User(String userName, String password) {

this.userName = userName;

this.password = password;

this.disabled = false;

this.firstConnection = this.lastConnection = new Date();

}

public User(String userName, String password, GroupEnum userGroup) {

this.userName = userName;

this.password = password;

this.userGroup = userGroup;

this.disabled = false;

this.firstConnection = this.lastConnection = new Date();

}

@Id(generate = GeneratorType.AUTO)

public Long getId() {

return id;

}

private void setId(Long id) {

this.id = id;

}

@Column(length = 32, unique = true)

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

@Column(length = 32)

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public boolean isDisabled() {

return disabled;

}

public void setDisabled(boolean disabled) {

this.disabled = disabled;

}

public Date getFirstConnection() {

return firstConnection;

}

public void setFirstConnection(Date firstConnection) {

this.firstConnection = firstConnection;

}

public Date getLastConnection() {

return lastConnection;

}

public void setLastConnection(Date lastConnection) {

this.lastConnection = lastConnection;

}

@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST,

CascadeType.MERGE, CascadeType.REFRESH })

public Person getPerson() {

return person;

}

public void setPerson(Person person) {

this.person = person;

}

@Type(type = «group»)

@Column(length = 20)

public GroupEnum getUserGroup() {

return userGroup;

}

public void setUserGroup(GroupEnum userGroup) {

this.userGroup = userGroup;

}

/**

* Promouvoit ou dégrade un utilisateur. Pour ce faire, l’utilisateur source

* doit avoir au moins les droits qu’il tente d’attribuer

*

* @todo considérer le cas de la dégradation (source doit avoir au moins les

* droits de l’utilisateur)

* @param source

* Utilisateur à l’origine du changement

* @param promotion

* Nouveau groupe

*/

@Transient

public void promoteUser(User source, GroupEnum promotion)

throws AccessRightsViolationException {

if (source.getUserGroup().compareTo(promotion) >= 0) { // La source

// doit avoir au

// moins les

// droits de la

// promotion

this.userGroup = promotion;

} else {

throw new AccessRightsViolationException(«User »

+ source.getUserName() + » can’t promote with » + promotion);

}

}

@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, mappedBy = «userWatches»)

public Set<Request> getRequestWatches() {

return requestWatches;

}

public void setRequestWatches(Set<Request> requestWatches) {

this.requestWatches = requestWatches;

}

@Transient

public void addRequestWatch(Request request) {

if (!this.requestWatches.contains(request)) {

this.requestWatches.add(request);

request.addWatch(this);

}

}

@Transient

public void removeRequestWatch(Request request) {

requestWatches.remove(request);

request.removeWatch(this);

}

@Transient

public boolean isWatching(Request request) {

return this.requestWatches.contains(request);

}

@Transient

public boolean isPromotable() {

return (userGroup.isItAdmin() || userGroup.isItUser());

}

@Transient

public boolean isDegradable() {

return (userGroup.isItAdmin() || userGroup.isSuperUser());

}

@Transient

public void promote() {

if (userGroup.isItAdmin())

userGroup = GroupEnum.SUPERUSER;

else if (userGroup.isItUser())

userGroup = GroupEnum.ITREQUEST_ADMIN;

}

@Transient

public void degrade() {

if (userGroup.isItAdmin())

userGroup = GroupEnum.ITREQUEST_USER;

else if (userGroup.isSuperUser())

userGroup = GroupEnum.ITREQUEST_ADMIN;

}

@Override

public int hashCode() {

if (id != null) {

return new HashCodeBuilder().append(id).toHashCode();

} else {

return super.hashCode();

}

}

@Override

@Transient

public String toString() {

return new ToStringBuilder(this).append(«userName», userName).append(

«disabled», disabled).toString();

}

@Override

@Transient

public boolean equals(Object o) {

if (o instanceof User) {

User user = (User) o;

return (id != null) ? id.equals(user.getId())

: super.equals(o);

}

return false;

}

@Transient

public int compareTo(Object obj) {

User user = (User) obj;

return this.userName.compareTo(user.getUserName());

}

}

Code between sessionFactory.openSession() and session.close():

N/A

Full stack trace of any exception that occurs:

_Exception:_

javax.ejb.EJBTransactionRolledbackException: null; CausedByException is:

could not execute query

at org.jboss.ejb3.tx.Ejb3TxPolicy.handleInCallerTx(Ejb3TxPolicy.java:65)

at org.jboss.aspects.tx.TxPolicy.invokeInCallerTx(TxPolicy.java:117)

at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:138)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:72)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:93)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:148)

at org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:65)

at $Proxy82.findByGroup(Unknown Source)

at be.sysmedit.services.itrequest.ApplicationServiceBean.checkAdmin(ApplicationServiceBean.java:249)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:585)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:99)

at org.jboss.ejb3.AllowedOperationsInterceptor.invoke(AllowedOperationsInterceptor.java:33)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:66)

at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:134)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:72)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:93)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessContainer.dynamicInvoke(StatelessContainer.java:183)

at org.jboss.aop.Dispatcher.invoke(Dispatcher.java:107)

at org.jboss.aspects.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:30)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:79)

at $Proxy94.checkAdmin(Unknown Source)

at be.sysmedit.web.admin.ApplicationBean.verifySetup(ApplicationBean.java:50)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:585)

at org.apache.myfaces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:138)

at oracle.adf.view.faces.component.UIXComponentBase.__broadcast(UIXComponentBase.java:1097)

at oracle.adf.view.faces.component.UIXCommand.broadcast(UIXCommand.java:204)

at javax.faces.component.UIViewRoot._broadcastForPhase(UIViewRoot.java:110)

at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:184)

at org.apache.myfaces.lifecycle.LifecycleImpl.invokeApplication(LifecycleImpl.java:271)

at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:102)

at javax.faces.webapp.FacesServlet.service(FacesServlet.java:109)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl._doFilterImpl(AdfFacesFilterImpl.java:310)

at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl.doFilter(AdfFacesFilterImpl.java:183)

at oracle.adf.view.faces.webapp.AdfFacesFilter.doFilter(AdfFacesFilter.java:87)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)

at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)

at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:153)

at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)

at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)

at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)

at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)

at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)

at java.lang.Thread.run(Thread.java:595)

org.hibernate.exception.SQLGrammarException: could not execute query

at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:59)

at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)

at org.hibernate.loader.Loader.doList(Loader.java:1861)

at org.hibernate.loader.Loader.list(Loader.java:1842)

at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:407)

at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:273)

at org.hibernate.impl.SessionImpl.list(SessionImpl.java:850)

at org.hibernate.impl.QueryImpl.list(QueryImpl.java:74)

at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:41)

at be.sysmedit.persistence.core.app.UserDAOBean.findByGroup(UserDAOBean.java:109)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:585)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:99)

at org.jboss.ejb3.AllowedOperationsInterceptor.invoke(AllowedOperationsInterceptor.java:33)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.tx.TxPolicy.invokeInCallerTx(TxPolicy.java:113)

at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:138)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:72)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:93)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:148)

at org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:65)

at $Proxy82.findByGroup(Unknown Source)

at be.sysmedit.services.itrequest.ApplicationServiceBean.checkAdmin(ApplicationServiceBean.java:249)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:585)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:99)

at org.jboss.ejb3.AllowedOperationsInterceptor.invoke(AllowedOperationsInterceptor.java:33)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:66)

at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:134)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:72)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:39)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:63)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:93)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessContainer.dynamicInvoke(StatelessContainer.java:183)

at org.jboss.aop.Dispatcher.invoke(Dispatcher.java:107)

at org.jboss.aspects.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:30)

at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:88)

at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:79)

at $Proxy94.checkAdmin(Unknown Source)

at be.sysmedit.web.admin.ApplicationBean.verifySetup(ApplicationBean.java:50)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:585)

at org.apache.myfaces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:138)

at oracle.adf.view.faces.component.UIXComponentBase.__broadcast(UIXComponentBase.java:1097)

at oracle.adf.view.faces.component.UIXCommand.broadcast(UIXCommand.java:204)

at javax.faces.component.UIViewRoot._broadcastForPhase(UIViewRoot.java:110)

at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:184)

at org.apache.myfaces.lifecycle.LifecycleImpl.invokeApplication(LifecycleImpl.java:271)

at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:102)

at javax.faces.webapp.FacesServlet.service(FacesServlet.java:109)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl._doFilterImpl(AdfFacesFilterImpl.java:310)

at oracle.adfinternal.view.faces.webapp.AdfFacesFilterImpl.doFilter(AdfFacesFilterImpl.java:183)

at oracle.adf.view.faces.webapp.AdfFacesFilter.doFilter(AdfFacesFilter.java:87)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)

at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)

at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:153)

at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)

at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)

at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)

at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)

at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)

at java.lang.Thread.run(Thread.java:595)

Caused by: java.sql.SQLException: ERROR: operator does not exist: character varying = bytea

at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:1471)

at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1256)

at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:175)

at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:389)

at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:330)

at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:240)

at org.jboss.resource.adapter.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:296)

at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:120)

at org.hibernate.loader.Loader.getResultSet(Loader.java:1537)

at org.hibernate.loader.Loader.doQuery(Loader.java:638)

at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:221)

at org.hibernate.loader.Loader.doList(Loader.java:1858)

… 90 more

Name and version of the database you are using:

PostgreSQL 8.0.3

The generated SQL (show_sql=true):

select user0_.id as id, user0_.disabled as disabled3_, user0_.password as password3_, user0_.userName as userName3_, user0_.firstConnection as firstCon5_3_, user0_.lastConnection as lastConn6_3_, user0_.person_id as person8_3_, user0_.userGroup as userGroup3_ from USERS user0_ where user0_.userGroup=?

Debug level Hibernate log excerpt:

The error org.postgresql.util.PSQLException: ERROR: operator does not exist: my_enum_type = character varying can be fixed by using implicit conversions in PostgreSQL or using explicit conversions by passing the java.sql.Types.OTHER to Spring JDBC.

The exception you will receive

When using Spring JDBC or Spring Data JDBC and custom Java enum types, you might run into the following problem:

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM your_table where enum_column = :enum_value;] nested exception is org.postgresql.util.PSQLException: ERROR: operator does not exist: my_enum_type = character varying

Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

The exception can occur if you are having enums with either

  1. or you are trying to persist an Spring Data JDBC entity with a repository save method
  2. executing a query on your own with one of Spring JDBC’s jdbcTemplate methods like query

Making Spring Data JDBC’s save method work with enumerations

With Spring Data JDBC you have probably an SQL definition like

CREATE TYPE my_enum_type AS ENUM('VALUE_1','VALUE_2')

CREATE TABLE my_table (enum_column my_enum_type);

The belonging Java source code will look like

public enum MyEnumType {
	VALUE_1, VALUE_2
}

@Table("my_table")
public class MyEntity {
	private MyEnumType type;
	// getter & setter ...
}

@Repository
public class MyTableRepository extends CrudRepository</* ... */> {
}

@Controller
public class MyTableController {
	@Autowired
	MyTableRepository
    
	@GetMapping("/")
	public void save() {
		MyEntity entity = new MyEntity();
		entity.setType(MyEnumType.VALUE_1);
		repository.save(entity);
	}
}

As soon as you try to call repository.save you will receive an exception. The problem is, that Spring Data JDBC does not support enumerations at the moment. See Jens Schauder’s answer at stackoverflow.

Jens does also link to another SO answer which describes how to solve the problem. To make the code sample above working, we can use PostgreSQL’s implicit conversion feature as described in the linked answer. The following SQL definition would reside somewhere in your Liquibase or Flyway migration definition:

<!-- Liquibase migration definition -->
<!-- as described above -->
<sql>CREATE TYPE my_enum_type AS ENUM('VALUE_1','VALUE_2')</sql>

<!-- add an additional type -->
<sql>CREATE CAST (varchar AS my_enum_type) WITH INOUT AS IMPLICIT</sql>

With help of the described CREATE CAST PostgreSQL will automatically try convert each String/varchar into the specified enum. You can now do something like

SELECT * FROM my_table WHERE enum_column = 'VALUE_1';
-- OR
INSERT INTO my_table(enum_column) VALUES('VALUE_1')

After that, repository.save() will work.

Using JdbcTemplate and enumerations

You might think that the specified CREATE CAST definition would also work for something like that:

public class MyRepository {
	@Autowired
    NamedParameterJdbcTemplate jdbcTemplate;

	public List<String> findAll() {
		MapSqlParameterSource parameters = new MapSqlParameterSource("type", MyEnumType.VALUE_1);
		
		return jdbcTemplate
			.queryForList("SELECT enum_column FROM my_table WHERE enum_column = :type", parameters);
	}
}

But this will drive you right into the exception you find at the beginning:

org.postgresql.util.PSQLException: ERROR: operator does not exist: my_enum_type = character varying

The reason for this behavior is how PostgreSQL handles the type casts. This Stackoverflow answer describes the reasons in detail. Spring JDBC does automatically convert the enum value into a Java String type and assigns it to the prepared statement. The underlying PgJDBC drivers then assigns the java.sql.Type.VARCHAR as type for this prepared statement parameter. Due to the assignment of the java.sql.Type, PostgreSQL will no longer try to apply our CREATE CAST conversion.

Solving it by configuration

You can configure your JDBC URL to use the parameter stringtype with value undefined. Each String parameter previously set with setString() will then not have the type definition java.sql.Type.VARCHAR. PostgreSQL applies will then apply our CREATE CAST definition.

Solving it programatically

If you don’t globally want to set stringtype to undefined, you have to use the java.sql.Types.OTHER when adding a value to the MapSqlParameterSource:

// does NOT WORK: 
// .addValue("type", MyEnumType.VALUE_1))
// one of the following does work:
.addValue("type", "VALUE_1", java.sql.Types.OTHER)
// or
.addValue("type", MyEnumType.VALUE_1.getName(), java.sql.Types.OTHER)
// or
.addValue("type", MyEnumType.VALUE_1, java.sql.Types.OTHER)

To make it more convenient, you can extend from MapSqlParameterSource to get something like this:

public static class CustomMapSqlParameterSource extends MapSqlParameterSource {
	public CustomMapSqlParameterSource addEnum(String paramName, Object value) {
		if (!value.getClass().isEnum()) {
			throw new IllegalArgumentException("Given parameter is not of Java type enum");
		}

		addValue(paramName, value, java.sql.Types.OTHER);

		return this;
	}
}

Wrapping it up

This blog post showed you, how you can use native PostgreSQL enumerations with native Java and make them both work with Spring Data JDBC and Spring JDBC.

Submitted by nasrin788_1384620 on Tue, 12/08/2020 — 07:37

Hi

I’ve been using Bonita for two years and developed some processes and reports well.

Almost all reports use custom query, some of them call query by rest API and others call them direct.

For example:

../API/extension/myreport?p={{pageNumber — 1}}&c={{numberOfItems}}{{params}}

or

../API/bdm/businessData/org.iut.model.table?q=findReq&p={{pageNumber — 1}}&c={{pageSize}}{{params2}}

But there is a weird problem in both methods that I have not seen before. It’s fine in local but on the server it doesn’t run when value of parameter in null or empty !!

I am getting the following error message in first method:

org.bonitasoft.console.common.server.page.RestApiRenderer Error when executing rest api extension call to apiExtension|GET|myreport

groovy.lang.MissingMethodException: No signature of method: static org.iut.model.myTableDAO.findReq() is applicable for argument types: (java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Integer, java.lang.Integer) values: [, , , , , 0, 2147483647]

and this error in second method:

Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying ~~ bytea
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

I changed query over and over but I can’t success.

first query is like this:

SELECT w
FROM mytable w
WHERE ( w.a like CONCAT(‘%’, :applicantname , ‘%’) OR :applicantname IS NULL)
AND ( w.b like CONCAT(‘%’, :applicantusername , ‘%’) OR :applicantusername IS NULL)
AND ( w.c like CONCAT(‘%’, :department , ‘%’) OR :department IS NULL )
AND ( w.tim <= :untilDate OR :untilDate IS NULL )
AND ( w.tim>= :fromDate OR :fromDate IS NULL )
ORDER BY w.persistenceId desc

I added lower funtion in query but it dosn’t work!

Then I added checking null in first of query ….

Then I summarized query and removed 2 parameters and changed name of paramet like defaults, but it dsn’t work !!!

SELECT w
FROM wkshpRequest w
WHERE ( :a IS NULL OR w.a like CONCAT(‘%’, :a, ‘%’) )
AND ( :b IS NULL OR w.b like CONCAT(‘%’, :b, ‘%’) )
AND ( :c IS NULL OR w.c like CONCAT(‘%’, :c, ‘%’) )
ORDER BY w.persistenceId desc

All of above qeuries in local and h2 database is OK but in the server and Postgres doesn’t work!!!

I’m using Bonita Community 7.8.4 and Postgres 9.6 on the server.

  • 11607 reads

Submitted by emmanuel.duchas… on Mon, 12/28/2020 — 17:08

Hi,

First thing that pulled my attention: static org.iut.model.myTableDAO.findReq() this is weird that your DAO contains static methods.

DAO classes are generated by Bonita and should not be static. Can you send the BDM you are using, along with the REST API Extension that makes the DAO call, just to make sure the code is not weird and may not «succeed» on H2 for bad reasons…

There are also threads on StackOverflow that may point to same problems as yours: https://stackoverflow.com/search?q=character+varying+bytea

Regards,

  • 210 reads

Контрольный список устранения неполадок:

# 1: В зависимости от типа используемой базы данных вы можете найти имена столбцов и их соответствующие типы данных с помощью этой команды SQL:

SELECT
   table_name,
   column_name,
   data_type
FROM
   information_schema.columns
WHERE
   table_name = 'the-name-of-the-table-in-the-database';

Ожидаемые результаты дадут вам три столбца; и особенно столбец data_type.

Убедитесь, что ваш класс Pojo и соответствующие типы данных соответствуют друг другу.

Обратите внимание: bigint (тип данных) в таблице внутри базы данных может легко совпадать с Long. целое с внутр. символ, варьирующийся в зависимости от строки или основного класса Java, например. класс, хранящий Enums, и так далее.

После подтверждения вышеизложенного выполните следующую проверку -> устранение неполадок:

# 2 : Основная проверка при устранении неполадок заключается в том, чтобы убедиться, что все типы данных полностью совпадают. И обратите внимание на параметры, передаваемые в запрос.

Передача перечисления или любого другого типа данных или типа перечисления, не соответствующего типам данных SQL, может вызвать ошибку (ошибки) «не сопоставлена», даже если класс pojo идеально соответствует структуре таблицы в базе данных.

пример pojo: UserAccountBalance.class

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;

@Builder//Lombok
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Data//Lombok
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Schema
@Entity(name = "user_account_balance")
@Table(name = "user_account_balance")
public class UserAccountBalance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @NotNull
    @Column(name = "username", nullable = false)
    private String userName;

    @NotNull
    @Column(name="currency_code", nullable = false)
    @Enumerated(EnumType.STRING)
    private CurrencyCode currencyCode;

    @NotNull
    @Column(name = "balance", nullable = false)
    private BigDecimal balance;

//Could be placed into and AuditModel class
    @Column(name = "datecreated", nullable = false, updatable = false)
    @JsonIgnore
    @DateCreated
    @CreationTimestamp
    private LocalDateTime dateCreated;

    @Column(name = "date_updated", nullable = false, updatable = false)
    @JsonIgnore
    @DateUpdated
    private LocalDateTime dateUpdated;

    @NotNull
    @Column(name = "active")
    @JsonIgnore
    private int active;

    @Column(name = "deleted")
    @JsonIgnore
    private int deleted;

}

Класс репозитория:

//Вариант 1: UserAccountBalanceRepository.class

@Repository
public abstract class UserAccountBalanceRepository implements CrudRepository<UserAccountBalance, Long> {

    private final EntityManager entityManager;

    public UserAccountBalanceRepository(@CurrentSession EntityManager entityManager){
        this.entityManager = entityManager;
    }

    @Transactional(readOnly = true)
    @Query(
            value="SELECT uab.*" +
                    " FROM public.user_account_balance uab" +
                    " WHERE (currency_code =cast(:currencyCode AS text)" +
                    " AND userName =:userName" +
                    " AND active =:active)",
            countQuery = "SELECT uab.*" +
                    " FROM public.user_account_balance uab" +
                    " WHERE (currency_code = cast(:currencyCode AS text)" +
                    " AND userName =:userName" +
                    " AND active =:active)",
            nativeQuery = true
    )
    public abstract Optional<UserAccountBalance> findByUserAccountBalance_UserName_And_CurrencyCode(
            String userName,
            CurrencyCode currencyCode,
            int active
    );

}

//Вариант 2: UserAccountBalanceRepository.class

@Repository
public abstract class UserAccountBalanceRepository implements CrudRepository<UserAccountBalance, Long> {

    private final EntityManager entityManager;

    public UserAccountBalanceRepository(@CurrentSession EntityManager entityManager){
        this.entityManager = entityManager;
    }

    @Transactional(readOnly = true)
    @Query(
            value="SELECT uab.*" +
                    " FROM public.user_account_balance uab" +
                    " WHERE (currency_code =:currencyCode" +
                    " AND userName =:userName" +
                    " AND active =:active)",
            countQuery = "SELECT uab.*" +
                    " FROM public.user_account_balance uab" +
                    " WHERE (currency_code = :currencyCode" +
                    " AND userName =:userName" +
                    " AND active =:active)",
            nativeQuery = true
    )
    public abstract Optional<UserAccountBalance> findByUserAccountBalance_UserName_And_CurrencyCode(
            String userName,
            String currencyCode,/*this is what truly worked out for me perfectly*/
            int active
    );

}

№3. Тестировать и еще раз тестировать. Если проблема не устранена, наберитесь терпения и еще раз просмотрите все свои переменные и классы.

№ 4. Если устранение неполадок с использованием варианта № 3 по-прежнему не помогает, подумайте о небольшой прогулке, небольшом отдыхе и свежим взглядом, чтобы посмотреть на все заново, начиная с устранения неполадок № 1.

Надеюсь, это поможет. Здоровья и мира.

#java #postgresql #jpa

Вопрос:

Я пытаюсь сохранить файл Excel и сохранить его в своей базе данных. Я получаю эту ошибку:

 Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause

org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying = bytea
Hint: No operator matches the given name and argument types. You might need to add explicit type casts. 
 

Это мой метод отправки сообщений контроллера:

 @PostMapping
public ResponseEntity<DocumentCreateResponse> addDocument(@RequestParam("file") MultipartFile file) throws IOException {
    Path copyLocation = Paths.get(uploadDir, Objects.requireNonNull(file.getOriginalFilename()));
    Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING);

    Document savedDocument = documentService.save(copyLocation.toAbsolutePath().toFile());
    if (savedDocument == null){
        return new ResponseEntity<>(new DocumentCreateResponse(null), null, HttpStatus.NOT_ACCEPTABLE);
    }
    return new ResponseEntity<>(new DocumentCreateResponse(savedDocument.getId()), null, HttpStatus.ACCEPTED);
}
 

Это класс документов:

 @Entity
public class DocumentEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name ="document_id")
    private Long id;

    @Column(name ="document_file")
    private File file;


    public DocumentEntity() {
    }

    public DocumentEntity(File file) {
        this.file = file;
    }
}
 

И это мой файл создания схемы (я использую Flyway и PostgreSQL)

 create table if not exists document_entity
(
    document_id bigserial
    constraint document_entity_document_id
    not null primary key,
    document_file varchar not null
);
 

Где я должен добавить изменения, чтобы мои файлы сохранялись правильно и не вызывали эту ошибку? Я читал статьи и видел эту ошибку, но я не вижу, что я должен изменить в своем коде.

 public class DocumentService implements DocumentServicePort {
    private final DocumentRepository documentRepository;

    public DocumentService(DocumentRepository documentRepository) {
        this.documentRepository = documentRepository;
    }

    @Override
    public Document save(File file) {
        Document document = new Document(file);
        if (document.hasValidExtension(document)) {
            documentRepository.saveDocument(document);
            return document;
        }
        return null;
    }
}
 

Комментарии:

1. пожалуйста, добавьте также свой класс репозитория. в чем заключается реализация documentService.save

2. Я добавляю класс DocumentService в post, documentRepository имеет только один метод сохранения документа(Документ-документ);

3. метод hasValidExtension проверяет , правильно ли расширение, если нет, он не возвращает документ

4. вы используете JPA для сохранения или запроса?

5. Я использую JPA .

Ответ №1:

Вы объявили свой файл как varchar в базе данных, где в вашем приложении вы объявили это поле как Файл.

Вы можете сделать несколько вещей, но для случая, о котором вы упомянули, измените тип столбца в базе данных. Это должно быть «bytea».

запустите это в бд (лучше, если таблица пуста):

 ALTER TABLE document_entity ALTER COLUMN document_file TYPE bytea USING document_file::TEXT::BYTEA;
 

Комментарии:

1. Это не работает, все равно получается та же ошибка. Я даже удалил базу данных и настроил ее снова, но она не работала

2. да, это так, так что я понятия не имею, что происходит

3. вы проверили, был ли тип столбца обновлен до bytea?

4. используйте @Lob аннотацию к полю файла в классе сущностей и измените тип переменной на byte[]

  •  
  • postgresql

  • hibernate

  •  07-06-2021
  •  | 

  •  

Question

I have a table in postgres with the following structure

CREATE TABLE rpaul."HK_LOGIN_DETAILS"
(
  "HK_LOGIN_DETAILS_ID" bigint NOT NULL,
  "HK_LOGIN_DETAILS_USERNAME" character varying(10) NOT NULL,
  "HK_LOGIN_DETAILS_PASSWORD" character varying(50) NOT NULL,
  CONSTRAINT "HK_LOGIN_DETAILS_PK" PRIMARY KEY ("HK_LOGIN_DETAILS_ID" ),
  CONSTRAINT "HK_LOGIN_DETAILS_UK" UNIQUE ("HK_LOGIN_DETAILS_USERNAME" )
)

And hibernate mapping for this table is as mentioned below

<hibernate-mapping package="net.rpaul.projects.homekeeping.domain.login">
    <class name="LoginDetails" table="`HK_LOGIN_DETAILS`">
        <id name="id" column="`HK_LOGIN_DETAILS_ID`" type="long">
            <generator class="assigned" />
        </id>
        <property name="userName" type="string" column="`HK_LOGIN_DETAILS_USERNAME`" not-null="true" />
        <property name="password" type="string" column="`HK_LOGIN_DETAILS_PASSWORD`" not-null="true" />
    </class>
</hibernate-mapping>

In the LoginDetails.java, I have declared id field as long, userName and password fields as String. Still when I try to execute the following

List list =  getHibernateTemplate().find("from LoginDetails ld where ld.userName = ?", userName);

I get

ERROR: operator does not exist: character varying = bytea

I am not getting what has went wrong. Any help would be appreciated.

No correct solution

OTHER TIPS

I think you should check that your variable «userName» is not null. I experienced this message in cases like that.

It seems that Hibernate is for some reason sending the type-parameter as bytea (or rather, probably java.sql.Types.BLOB), instead of leaving it for the server to infer or setting it to text (java.sql.Types.STRING).
Here is similar issue with solution JPA lower() function on parameter

The question is old but still sharing my solution I’ve used in Spring Boot if anyone needed.

You can use the below WHERE conditions for handling NULL values or making the parameters optional in the Postgres Query.

SELECT * FROM table 
WHERE 
          (?1 is null OR column1 = cast(?1 AS text)) 
          AND 
          (?2 is null OR column2 = cast(?2 AS text))

Here whole WHERE condition will be TRUE if column1 and column2 are passed as NULL.
column1 and column2 will be considered in the query if not NULL.

?1 is null OR column1 = ?1 : will check if passed value is null, then whole where condition will be true (will not check for second condition [column1 = null] if null — PG Optimization)

cast(?1 AS text) : can be useful if for some reason value is passed as bytea. If the passed value is real null, it will still give the «character varying bytea» error if not casted.

For Native Query we can use

SELECT * FROM table 
WHERE 
          (:paramName is null OR column1 = cast(:paramName AS text)) 

and then

query.setParamter(paramName,value);

Понравилась статья? Поделить с друзьями:
  • Error operation failed active console session exists for this domain
  • Error openvz vps is not supported
  • Error opening zip file or jar manifest missing idea
  • Error opening xml plugin file
  • Error opening video check your display settings