getting Caused by: org.hibernate.QueryException: cannot dereference scalar collection element: roles - spring-boot

I have this class , and i'am trying to acess mobileNumbers and roles from the user table , but being lazy intialized i keep getting 'lazy intialization error.
I do not wan't to remove the LAZY fetch as complete access of the object is rarely required , but is required. So to overcome it first i tried to add #Transactional but going by this article https://codete.com/blog/5-common-spring-transactional-pitfalls/ it seems a bad approch in my case, i tried using join fetch but it keeps giving multiplebagfetchexception ,hence i tried to fetch them one at a time ( Element Collections i mean)
with this repository class
public interface UserRespository extends JpaRepository<UserDao, Long> {
Optional<UserDao> getByUserNameIgnoreCase(String userName);
// Optional<UserDao> findByUserNameIgnoreCase(String userName);
#Query(value = "select dao.roles.roles from UserDao dao inner join dao.roles r on dao.userName in elements(r.userName) and upper(dao.userName) = upper(?1)")
Object getByUserNameIgnoreCaseComplete2(String userName);
}
then i get his error
Caused by: org.hibernate.QueryException: cannot dereference scalar collection element: roles
at org.hibernate.persister.collection.ElementPropertyMapping.toType(ElementPropertyMapping.java:33) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.persister.collection.AbstractCollectionPersister.toType(AbstractCollectionPersister.java:1644) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:396) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:515) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:682) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:265) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:205) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:114) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:109) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:104) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.tree.DotNode.resolveSelectExpression(DotNode.java:744) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.HqlSqlWalker.resolveSelectExpression(HqlSqlWalker.java:1057) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2295) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2232) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1503) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:585) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:271) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:191) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
... 112 common frames omitted
I'm not sure why i keep getting this error.Is there any other way i can get the entire object??
Please help.
The actual class
#Entity
#Table(name = "users")
#Data
#NoArgsConstructor
public class UserDao implements Serializable {
#Id
#GeneratedValue
private long id;
#Column(name = "user_name", nullable = false, unique = true)
private String userName;
#Column(name = "password", nullable = false)
private String password;
#ElementCollection(targetClass = java.lang.String.class)
#CollectionTable(name = "mobile_numbers_List",joinColumns = #JoinColumn(name = "user_name",referencedColumnName = "user_name"))
#Column(name = "mobile_number")
private List<String> mobileNumbers;
#ElementCollection(targetClass = java.lang.String.class)
#CollectionTable(name = "roles_list",joinColumns = #JoinColumn(name = "user_name",referencedColumnName = "user_name"))
#Column(name = "roles")
private List<String> roles;
}

This seems like a similar question you previous question , and the answer to the previous one and this one is same.
your query is wrong here
#Query(value = "select dao.roles.roles from UserDao dao inner join dao.roles r on dao.userName in elements(r.userName) and upper(dao.userName) = upper(?1)")
Object getByUserNameIgnoreCaseComplete2(String userName);
it's trying to fetch dao.roles.roles which if does not even exist.
here are some changes you should try
change dao.roles.roles to r (as you already created an alias , let's use it)
remove dao.userName in elements(r.userName) it's not required, spring does this automatically without even specifying it.
change the return type to list , it's ElementCollection i.e Collection of elements
this is how your final query would look like
#Query(value = "select r from UserDao dao inner join dao.roles r on upper(dao.userName) = upper(?1)")
List<String> getByUserNameIgnoreCaseComplete2(String userName);

Why did u comment out findByUserNameIgnoreCase ? findBy Worked for me
Take a peek in this page

The Problem is the dao.roles.roles in your query. Change it to dao.roles.
dao.roles in your case is a List<String> and a String does not have a property roles.

Related

Spring JPA Repository - Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet

I have a Repository and hitting directly this repository from Postman.
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2115)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1874)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2610)
at org.hibernate.loader.Loader.doList(Loader.java:2593)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2422)
at org.hibernate.loader.Loader.list(Loader.java:2417)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1980)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:114)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:78)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:102)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:92)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 98 common frames omitted
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=RCON411.PROJECT, DRIVER=4.11.69
at com.ibm.db2.jcc.am.gd.a(gd.java:676)
at com.ibm.db2.jcc.am.gd.a(gd.java:60)
at com.ibm.db2.jcc.am.gd.a(gd.java:127)
at com.ibm.db2.jcc.am.jn.c(jn.java:2561)
at com.ibm.db2.jcc.am.jn.d(jn.java:2549)
at com.ibm.db2.jcc.am.jn.a(jn.java:2025)
at com.ibm.db2.jcc.am.kn.a(kn.java:6836)
at com.ibm.db2.jcc.t4.cb.g(cb.java:140)
at com.ibm.db2.jcc.t4.cb.a(cb.java:40)
at com.ibm.db2.jcc.t4.q.a(q.java:32)
at com.ibm.db2.jcc.t4.rb.i(rb.java:135)
at com.ibm.db2.jcc.am.jn.ib(jn.java:1996)
at com.ibm.db2.jcc.am.kn.sc(kn.java:3058)
at com.ibm.db2.jcc.am.kn.b(kn.java:3841)
at com.ibm.db2.jcc.am.kn.fc(kn.java:702)
at com.ibm.db2.jcc.am.kn.executeQuery(kn.java:672)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:82)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:82)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
... 127 common frames omitted
Project class is
#Data #Entity #Table(name = "PROJECT", schema = "DCS") public class Project implements Identifiable<Integer> {
#Id
#Column(name = "PRJ_I", nullable = false)
private Integer id;
#Column(name = "PRJ_NM")
private String projectName;
#OneToOne
#JoinColumn(name="PRJ_I")
private CcpaCustomerProjectGroup ccpaCustomerProjectGroup;
}
CcpaCustomerProjectGroup is
#Data #Entity #Table(name = "CCPA_CUS_PRJ_GRP", schema = "DCS") public class CcpaCustomerProjectGroup implements Identifiable<Integer> {
#Id
#Column(name="CCPA_CUS_PRJ_GRP_I")
private Integer id;
#Column(name="CUS_PRJ_GRP_I")
private Integer customerProjectGroupId;
#Column(name="PRJ_I")
private Integer projectId;
/*#OneToOne
#PrimaryKeyJoinColumn
private Project project;*/
}
ProjectRepository is
public interface ProjectRepository extends JpaRepository<Project, Integer>,JpaSpecificationExecutor<Project>, QueryDslPredicateExecutor<Project> {
#Query(value="select p.PRJ_I,p.PRJ_NM from CCPA_CUS_PRJ_GRP c,project p where c.CUS_PRJ_GRP_I = ?1 and c.PRJ_I = p.PRJ_I and p.PRJ_NM like ?2", nativeQuery = true)
List<Project> find(#Param("clientId") Integer clientId, #Param("projectName") String projectName);
}
As already stated by JB in the comments, this is the important part of the stack trace:
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=RCON411.PROJECT, DRIVER=4.11.69
First confirm that DCS.PROJECT exists in the datasource you are working with, and that the user you are connecting with in your application has the necessary grants to view it.
Similarly, Looks like the PROJECT table might be trying to get accessed from the wrong schema. Does the user you are using to connect to DB2 in your app have access to the DCS schema? And if so, you may need to set the CURRENT_SCHEMA to be DCS.

SQL0913 Row or object table in Schema type *FILE in use

I am having a transaction using spring data , and I am trying to do an save operation (insert operation) . [SQL0913] Row or object table in Schema type *FILE in use.
Following is the entity
#Entity
#IdClass(OsytxlId.class)
#Table(name="OSYTXL")
#NamedQuery(name="Osytxl.findAll", query="SELECT o FROM Osytxl o")
public class Osytxl implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="TLCONO")
private BigDecimal tlcono;
#Id
#Column(name="TLDIVI")
private String tldivi;
#Id
#Column(name="TLLINO")
private BigDecimal tllino;
#Column(name="TLLMTS")
private BigDecimal tllmts;
#Id
#Column(name="TLLNCD")
private String tllncd;
#Column(name="TLTX60")
private String tltx60;
#Id
#Column(name="TLTXID")
private BigDecimal tltxid;
#Id
#Column(name="TLTXVR")
private String tltxvr;
//getter and setters
}
I am using springdata-jpa
And I am calling the following code portion from the service implementation class
Before the following insertion , I need to delete the contents before insert .
Osytxl osytxl = null;
Collection<Osytxl> osytxlList = new ArrayList<Osytxl>();
for (int lineNo = 0; lineNo < lines.length; lineNo++) {
osytxl = new Osytxl();
osytxl.setTlcono(osytxh.getThcono());
osytxl.setTldivi(osytxh.getThdivi());
osytxl.setTltxid(osytxh.getThtxid());
osytxl.setTltxvr(osytxh.getThtxvr());
osytxl.setTllncd(osytxh.getThlncd());
osytxl.setTllmts(new BigDecimal("1437651510403"));
osytxl.setTllino(new BigDecimal(lineNo+1));
osytxl.setTltx60(lines[lineNo]);
osytxlList.add(osytxl);
}
if(osytxlList.size()>0)
osytxlRepository.save(osytxlList);
And I am using JPA repository But I am getting the following exception
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.GenericJDBCException: could not execute statement; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:415)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:418)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy107.saveAndFlush(Unknown Source)
........................................................
Caused by: java.sql.SQLException: [SQL0913] Row or object OSYTXL in schema type *FILE in use.
at com.ibm.as400.access.JDError.createSQLExceptionSubClass(JDError.java:877)
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:706)
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:676)
at com.ibm.as400.access.AS400JDBCStatement.commonExecute(AS400JDBCStatement.java:1021)
at com.ibm.as400.access.AS400JDBCPreparedStatement.executeUpdate(AS400JDBCPreparedStatement.java:1825)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 127 more
I am using iseries (DB2) .Am I missing something or there anything I need to do extra in persistence.xml . Can anyone help .
I've found on Experts Exchange that this could be due to queries outside of your application, locking the required records.
Adding FOR READ ONLY to your query like this:
SELECT * FROM FILE.TABLE
FOR READ ONLY

JpaSystemException: attempted to assign id from null one-to-one property

I'm using the Play framework with Spring and Hibernate, and I get the following error when I try to save an entity containing a one-to-one relationship to another entity
[play] Caused by: org.springframework.orm.jpa.JpaSystemException: attempted to assign id from null one-to-one property [org.famian.web.models.domains.StudyCriteria.ensatIdent]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [org.famian.web.models.domains.StudyCriteria.ensatIdent]
[play] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:244) ~[spring-orm-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:155) ~[spring-orm-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417) ~[spring-orm-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) ~[spring-tx-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) ~[spring-tx-4.0.7.RELEASE.jar:4.0.7.RELEASE]
[play] Caused by: org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [org.famian.web.models.domains.StudyCriteria.ensatIdent]
[play] at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:98) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.jpa.event.internal.core.JpaMergeEventListener.saveWithGeneratedId(JpaMergeEventListener.java:73) ~[hibernate-entitymanager-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:271) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
[play] at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:251) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
The 2 entities share a common primary key, below are my classes
#Entity
public class EnsatIdent implements Serializable {
#EmbeddedId
private EnsatIdentPK id;
#OneToOne(mappedBy = "ensatIdent", cascade = CascadeType.ALL)
private StudyCriteria studyCriteria;
}
#Entity
public class StudyCriteria {
#EmbeddedId
private EnsatIdentPK id;
#MapsId
#JoinColumns({
#JoinColumn(name = "center_id"),
#JoinColumn(name = "ensat_id")
})
#OneToOne
private EnsatIdent ensatIdent;
}
#Embeddable
public class EnsatIdentPK implements Serializable {
#Column(name = "center_id", columnDefinition = "varchar(5)")
private String centerId;
#Column(name = "ensat_id", columnDefinition = "int(11)")
private Integer ensatId;
}
My service class is a class called IdenService which extending the Spring PagingAndSortingRepository class. When I save, I called
IdenService service.save(ensatIdent)
If I do a System.out.println() on
ensatIdent.getStudyCriteria()
it shows
StudyCriteria(id=EnsatIdentPK(centerId=GYMU, ensatId=3))
It saves fine if the entity only contain Ident information, but if I add studyCriteria in the object, the error will occur. I don't understand what is happening, please help.
Solved, the problem was because StudyCriteria object does not have a reference of the EnsatIden object.
By adding
ensatIdent.getStudyCriteria().setEnsatIdent(ensatIdent);
solved the error

JPA CriteriaBuilder: Predicate with a Serializable field throws an exception

I have an entity with a persistent field declared as Serializable.
I would like to build a query with the CriteriaBuilder, that filters the results by the Serializable field.
The database is Oracle, and the field type is RAW(255) as hbm2ddl defined it.
If i write the query with a plain JPQL TypedQuery, everything works fine (the Serializable field is the one with the name "entityId"):
TypedQuery<Change> query = em.createQuery("FROM Change c WHERE c.entityClass = :class AND c.entityId = :id", Change.class);
query.setParameter("class", Person.class.getName());
query.setParameter("id", new Integer(2287));
query.getResultList();
However, the very same query with criteria builder does not work:
final CriteriaBuilder builder = em.getCriteriaBuilder();
final CriteriaQuery<Change> criteriaQuery = builder.createQuery(Change.class);
final Root<Change> from = criteriaQuery.from(Change.class);
final CriteriaQuery<Change> select = criteriaQuery.select(from);
final List<Predicate> predicates = new ArrayList<>();
predicates.add(builder.equal(from.get("entityClass"), Person.class.getName()));
predicates.add(builder.equal(from.get("entityId"), new Integer(2287)));
select.where(predicates.toArray(new Predicate[predicates.size()]));
final TypedQuery<Change> query = em.createQuery(select);
query.getResultList();
It throws the following exception after invoking getResultList():
[2013-05-21 16:12:45,960] [com.mycompany.myproduct.server.Main.startServer(Main.java:56)] [ERROR] [main] - Error starting Server: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
...
Caused by: java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: expected BINARY got NUMBER
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
...
Change.java:
#Entity
#Table(name = "T_REVISION_CHANGE")
#SequenceGenerator(name = "seq_revision_change", sequenceName = "SEQ_REVISION_CHANGE", allocationSize = 1)
public class Change {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_revision_change")
private Integer id;
#Column(name = "ENTITY_CLASS")
private String entityClass;
#Column(name = "ENTITY_ID")
private Serializable entityId;
}
I tried to manually serialize the Integer but the same kind of exception was thrown saying that a Serializable instance was expected instead of a byte array... :)
Any comment would be much appreciated.

Hibernate LazyInitializationException when accessing a collection

I got the below Exception when i wnat to get the data from another table
17:38:45,823 ERROR [org.hibernate.LazyInitializationException] failed to lazily initialize a collection of role: com.sinergia.ea.model.TypeOfArtifactModel.checkedItems, no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.sinergia.ea.model.TypeOfArtifactModel.checkedItems, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358) [:3.2.6.ga]
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350) [:3.2.6.ga]
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343) [:3.2.6.ga]
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86) [:3.2.6.ga]
at org.hibernate.collection.PersistentSet.toString(PersistentSet.java:309) [:3.2.6.ga]
at java.lang.String.valueOf(String.java:2826) [:1.6.0_18]
at java.lang.StringBuilder.append(StringBuilder.java:115) [:1.6.0_18]
at com.sinergia.ea.view.TypeOfArtifactBean.editTypeOfArtifact(TypeOfArtifactBean.java:203) [:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_18]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [:1.6.0_18]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [:1.6.0_18]
at java.lang.reflect.Method.invoke(Method.java:597) [:1.6.0_18]
at org.apache.el.parser.AstValue.invoke(AstValue.java:196) [:6.0.0.Final]
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276) [:6.0.0.Final]
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [:2.1.3-SNAPSHOT]
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [:2.1.0-FCS]
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [:2.1.3-SNAPSHOT]
at javax.faces.component.UICommand.broadcast(UICommand.java:315) [:2.1.0-FCS]
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [:2.1.0-FCS]
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [:2.1.0-FCS]
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [:2.1.3-SNAPSHOT]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [:2.1.3-SNAPSHOT]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [:2.1.3-SNAPSHOT]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409) [:2.1.0-FCS]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:324) [:6.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242) [:6.0.0.Final]
Model Class :
#Entity
#Table(name="TYPE_OF_ARTIFACT")
public class TypeOfArtifactModel implements java.io.Serializable , Identifiable{
/**
*
*/
private static final long serialVersionUID = 2662289176706818360L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TYPE_OF_ARTIFACT_SEQ")
#SequenceGenerator(name = "TYPE_OF_ARTIFACT_SEQ", sequenceName = "TYPE_OF_ARTIFACT_SEQ")
#Column(name="ID",unique=true, nullable=false)
private Integer id;
#Column(name="DESCRIPTION", nullable=true, length=400)
private String description;
#Column(name="NAME", nullable=false, length=50)
private String name;
#OneToMany(targetEntity = AdditionalInfoModel.class, mappedBy = "typeOfArtifactID",cascade = CascadeType.ALL)
private Set<AdditionalInfoModel> additionalInfos = new HashSet<AdditionalInfoModel>(0);
#OneToMany
#JoinTable(name = "TYPE_ARTIFACT_OPERATE_RELATION", joinColumns = { #JoinColumn(name = "TYPE_OF_ARTIFACT_ID") }, inverseJoinColumns = { #JoinColumn(name = "OPERATE_ARTIFACT_ID") })
private Set<TypeOfArtifactModel> checkedItems = new HashSet<TypeOfArtifactModel>(0);
public TypeOfArtifactModel() {
}
View bean
public String editTypeOfArtifact() {
additionalInfoModelList = additionalInfoService.getAdditionalInfoList(getCurrentItem());
setAdditionalInfoModelList(additionalInfoModelList);
if(getCurrentItem() != null){
Set<TypeOfArtifactModel> typeOfArtifactCheckedItems = getCurrentItem().getCheckedItems();
System.out.println("TypeOfArtifactCheckedItems :"+typeOfArtifactCheckedItems);
if(typeOfArtifactModelList != null && !(typeOfArtifactModelList.isEmpty())){
if(typeOfArtifactCheckedItems != null && !(typeOfArtifactCheckedItems.isEmpty())){
for (TypeOfArtifactModel item : typeOfArtifactModelList) {
for (TypeOfArtifactModel checkedItem : typeOfArtifactCheckedItems) {
if(item.getId()==checkedItem.getId()){
checked.put(checkedItem.getId().longValue(), true);
}
}
}
}
}
}
return null;
}
Set typeOfArtifactCheckedItems = getCurrentItem().getCheckedItems();
i got the above error at particular situation why it happens i don't know please give me a solution.
By default a #OneToMany collection e.g. checkedItems is lazily loaded by Hibernate. This means that when you load a TypeOfArtifactModel a proxy is created in place of the actual collection.
When you first access that collection Hibernate will attempt to load the required entities from the database. However, that load must take place using the same session as the original entity. In your case it appears that the session has been closed before you try to access the collection.
To avoid this you need to either:
Make the collection eager loaded using FetchType.EAGER (this is not advised)
Fetch the collection when you fetch the TypeOfArtifactModel using a HQL fetch join or using Hibernate.initialize(model.getCheckedItems())
You haven't shown any of your transaction management code but make sure you do the above before the session is closed (or transaction committed).
It's also worth pointing out that this gets asked about once a day on Stack Overflow.

Resources