"Not mapped" exception while updating the table in Hibernate - java

I am new to Hibernate, I am trying to update the table column like below, but it's giving an exception - table is not mapped exception.
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "UPDATE TEST_TABLE SET LAST_REFRESH_DATE = :dateToday";
Query query = session.createQuery(hqlUpdate);
query.setParameter("dateToday", new UtilityDate().getTodayDate());
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
Exception
SEVERE: Servlet.service() for servlet [springmvc] in context with path
[/TEST] threw exception [Request processing failed; nested exception
is org.hibernate.hql.ast.QuerySyntaxException: TEST_TABLE is not
mapped [UPDATE TEST_TABLE SET LAST_REFRESH_DATE = :dateToday]] with
root cause org.hibernate.hql.ast.QuerySyntaxException: TEST_TABLE is
not mapped [UPDATE TEST_TABLE SET LAST_REFRESH_DATE = :dateToday] at
org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:181)
at
org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
at
org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:94)
I've verified all related questions already in Stack Overflow.

In hibernate once after defining the table mappings we always communicate with system in terms of Object and Classes. As per the snippet you posted it seems you are using the database table name and its column name in the HQL which is wrong. Instead of this you need to specify the mapped table class name and its property name in place of table column name.
if table TEST_TABLE is mapped with Java class TestTable and lastRefreshDate is the property of this class mapped to LAST_REFRESH_DATE column then below should be the code.
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "UPDATE TestTable SET lastRefreshDate = :dateToday";
Query query = session.createQuery(hqlUpdate);
query.setParameter("dateToday", new UtilityDate().getTodayDate());
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Related

hibernate : binding parameter if not null

I create a web service which check an existence of data in a table. I had two input, one input is mandatory and the other is optional.
I want to create one query which binding the parameter mode if not null.
I used this query but it didn't work and I had this error:
java.sql.SQLException: ORA-01008: not all variables bound
query :
SELECT DATE_TRAITEMENT, DATE_DEB_PERIODE, DATE_FIN_PERIODE,user_cdg,canal,motif,SUJET_CRM,MODE_generation, TRAIT_STATUS,REMARK FROM ACM.CDG_REQUEST_OnDEMAND where CO_ID = :coId and (MODE_GENERATION= :mode or (MODE_GENERATION is null and :mode is null)) order by DATE_TRAITEMENT asc
and this my DAO class :
Session session = HibernateUtil.currentSession();
SQLQuery query = null;
org.hibernate.Transaction tx = session.beginTransaction();
String sql = cdg.getMessage("REQ001");
query = session.createSQLQuery(sql);
query.setLong("coId", coId);
if(integer != null) {
query.setInteger("mode", integer);
}
query.executeUpdate();

JPA EclipseLink - Get multiple objects by primary key maintaining order

I'm using EclipseLink as JPA implementation and I need to get multiple objects using the primary key (numeric id). But I also need to maintain the given id order.
Using native mySQL this kind of behaviour can be obtained using ORDER BY FIELD
SELECT id FROM table WHERE id IN(9,5,2,6) ORDER BY FIELD(id,9,5,2,6);
I'm now trying to replicate this query using JPA implementation. As already established from this thread, the ORDER BY FIELD is not supported, so I went to a more low-level approach using a JPA native query.
I'm try to reach this goal using a parameter query, instead of using a raw statement. The first implementation was like this
Class<?> clazz = ...;
List<Long> ids = ...;
EntityManagerFactory emf = ...;
EntityManager em = emf.createEntityManager();
String statement = "SELECT * FROM table WHERE id IN (?)";
Query createNativeQuery = em.createNativeQuery(statement, clazz);
createNativeQuery.setParameter(1, ids);
List resultList = createNativeQuery.getResultList();
As you can see the ORDER clause is not there yet, for the first step I just trying to make the parameter query work using the ids list with the IN operator. In the setParameter method I tried to provide the List object, a comma separated list (as string) but none of them works. At the end they all finish with a sql syntax error.
I also tried to play with the parenthesis, with or without, but nothing works.
Here some test I made
String statement = "SELECT * FROM " + tableName + " WHERE id IN (?)";
Query createNativeQuery = emJpa.createNativeQuery(statement, this.em.getClassObject());
createNativeQuery.setParameter(1, ids);
The query does not give any error, but no results given.
String statement = "SELECT * FROM " + tableName + " WHERE id IN (?)";
Query createNativeQuery = emJpa.createNativeQuery(statement, this.em.getClassObject());
createNativeQuery.setParameter(1, Joiner.on(",").join(ids));
Only one result is given, but 7 ids was provided to the query
From this topic I also tried using ?1 instead of ?, but no changes. Is there a way to make the nativeQuery working with a list of ids?
For the moment I'm using the full raw SQL statement
String joinedId = Joiner.on(",").join(ids);
String statement = "SELECT * FROM " + tableName + " WHERE id IN (" + joinedId + ") ORDER BY FIELD(id," + joinedId + ")";
Query createNativeQuery = emJpa.createNativeQuery(statement, this.em.getClassObject());
createNativeQuery.getResultList();
But at first I started with the parameter query for optimization and performance related of parsing each time the statement.
EDIT
With the suggestion of Chris I tried a TypedQuery using the FUNCTION operator (which is available because I'm using the latest EclipseLink). Here is the resulting code
List<Long> ids = ...;
Class<?> clazz = ...;
String statement = "SELECT e FROM " + clazz.getSimpleName() + " e WHERE e.id IN (:idList) ORDER BY FUNCTION('FIELD', e.id, :idList)";
EntityManagerFactory emf = ...;
EntityManager em = emf.createEntityManager();
TypedQuery<?> query = em.createQuery(statement, clazz);
query.setParameter("idList", ids);
List resultList = query.getResultList();
And here is the error while executing this code
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Operand should contain 1 column(s)
Error Code: 1241
Call: SELECT ... all the fields ... FROM webcontent_type WHERE (ID IN ((?,?,?,?,?,?,?))) ORDER BY FIELD(ID, (?,?,?,?,?,?,?))
bind => [14 parameters bound]
Query: ReadAllQuery(referenceClass=WebContentType sql="SELECT ... all the fields ... FROM webcontent_type WHERE (ID IN (?)) ORDER BY FIELD(ID, ?)")
EDIT 2
Tried without the parenthesis but there is still an error
SELECT e FROM FrameWorkUser e WHERE e.id IN :idList ORDER BY FUNCTION('FIELD', e.id, :idList)
I must say that with a list of one element the code works, but with another list of 10 elements there is an error
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.3.v20160428-59c81c5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Operand should contain 1 column(s)
Error Code: 1241
Call: SELECT .... FROM webcontent_type WHERE (ID IN (?,?,?,?,?,?,?)) ORDER BY FIELD(ID, (?,?,?,?,?,?,?))
bind => [14 parameters bound]
Query: ReadAllQuery(referenceClass=WebContentType sql="SELECT .... FROM webcontent_type WHERE (ID IN ?) ORDER BY FIELD(ID, ?)")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:382)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:473)
It seems that even w/o the parenthesis, the resulting statement has them
If you are going to use a native query, you must do it exactly like you would form the SQL for your database - this means you must break the list into its component parameters as JPA providers are not expected to change the SQL for you. Most providers handle lists in JPQL though, so "select e from Entity e where e.id in (:idList)" will work in EclipseLink.
Your missing bit is that 'FIELD' is not a JPQL construct. For this, you would have to use the JPQL 2.1 FUNCTION operator. Something like:
"Select e from Entity e where e.id in :idList order by FUNCTION('FIELD', e.id, :idList)"

Hibernate Exception - could not locate named parameter [:laboratoryId]

I have the following query in Hibernate.I got Hibernate Exception and I don't understand why Hibernate throws this exception. Could anyone help me?
Session session = this.sessionFactory.openSession();
session.createQuery("delete from Laboratory l where l.id=:laboratoryId")
.setParameter("laboratoryId", laboratoryId).executeUpdate();
session.close();
Try to add some spaces between the = sign and the bind name :laboratoryId and remove the alias:
Session session = this.sessionFactory.openSession();
session.createQuery("delete from Laboratory where id = :laboratoryId")
.setParameter("laboratoryId", laboratoryId)
.executeUpdate();
session.close();
Are you sure that laboratoryID has value? For my query builder I used something like this:
if (!laboratoryId.isEmpty()) {
query.setParameter("laboratoryId", laboratoryId());
}
also same thing for query
"delete o from Laboratory o"
if(!laboratoryId.isEmpty()){
query.append("where o.id = (:laboratoryId)")
}
But I used it for String values
Please show code for laboratoryId - is it user input or what?
You can try this one.
DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE clause:
String hql = "DELETE FROM Employee " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Postgresql JPA Hibernate create Database

I'm having trouble with Postgresql with JPA Hibernate.
My code :
#Transactional
public void createDatabase(User user) {
Query q = em.createNativeQuery("CREATE USER \"" + user.getEmail()
+ "\" WITH PASSWORD '" + user.getPasswordHash() + "' ;");
q.executeUpdate();
Query q1 = em.createNativeQuery("CREATE DATABASE " + user.getDb() + ";");
q1.executeUpdate();
Query q2 = em.createNativeQuery("GRANT ALL PRIVILEGES ON " + user.getDb()
+ " TO '" + user.getEmail() + "';");
q2.executeUpdate();
}
I'm having the following Error.
Hibernate: CREATE USER "test" WITH PASSWORD 'test' ;
Hibernate: CREATE DATABASE test;
2015-05-08 15:15:49.531 WARN 1952 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 25001
2015-05-08 15:15:49.531 ERROR 1952 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : ERREUR: CREATE DATABASE cannot be created in a transaction bloc
2015-05-08 15:15:49.545 ERROR 1952 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERREUR: CREATE DATABASE cannot be created in a transaction bloc
If i delete the Transaction Annotation i get the following error :
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:71)
at com.esisa.pfe.business.DefaultUserService.createDatabase(DefaultUserService.java:56)
at com.esisa.pfe.controllers.ClientController.addAbonnement(ClientController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
The JPA EntityManager is not the object to create new databases or users. see documentation what for entity manager is used. If you want to create a new database from java you can do this with simple JDBC - here some example code:
// without db name
public static final String HOST = "jdbc:postgresql://localhost:5432/";
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE JavaDB");
stmt.executeUpdate("CREATE USER java_user WITH PASSWORD \'java\'");
// ...
JPA 2.1 allows you to create the datastore tables etc (and optionally schema too depending on JPA implementation and datastore) when creating the EntityManagerFactory.

Getting org.hibernate.hql.ast.QuerySyntaxException though it works fine sql server?

i have below code snippet. It throws the exception at line 3 but query works fine managemnt studio(sql server 2005)
String query = "select * from user where userId=" + profileId
+ " and spaceName='" + spaceName + "'";
Session session = HibernateUtil.getSession();
List<PersonDetailsData> personDetailsData = new ArrayList<PersonDetailsData>(
session.createQuery(query).list()); //line 3
Here is the exception
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: * near
line 1, column 8 [select * from user where userId=216 and
spaceName='DIG']
I am not able to figure out what's the problem with query when it is running fine in management sudio?
It's native query, not hql.
If you have mapped table field to class fields you need
session.createSQLQuery(query, PersonDetailsData.class).list();
or create hql type query -
select p from PersonDetailData p where p.userId = :userId and p.spaceName =:spaceName
and use parameters in query, not direct values.
As you are using sql query so you have to create a sql query such as
sess.createSQLQuery("SELECT * FROM CATS").list();
see the source source

Categories

Resources