Hibernate gives me a run time error to the following query.It's saying that there is a syntax error.
ERROR: Syntax error: Encountered "," at line 1, column 16.
Note that transaction handling handled at the service layer that's why session related lines are not in the code.
String hql = "UPDATE Lecturer L set L.id=:id,L.name=:name,L.department=:department,L.center=:center,L.facultyType=:facultyType,L.rank=:rank,L.level=:level,L.building.id=:buildingId,L.building.building=:building where L.id=:prevId";
Query query = session.createQuery(hql);
query.setParameter("id", lecturerDTO.getId());
query.setParameter("name", lecturerDTO.getName());
query.setParameter("department", lecturerDTO.getDepartment());
query.setParameter("center", lecturerDTO.getCenter());
query.setParameter("facultyType", lecturerDTO.getFacultyType());
query.setParameter("rank", lecturerDTO.getRank());
query.setParameter("level", lecturerDTO.getLevel());
query.setParameter("buildingId", lecturerDTO.getBuildingDTO().getId());
query.setParameter("building", lecturerDTO.getBuildingDTO().getBuilding());
query.setParameter("prevId", prevId);
query.executeUpdate();
Related
I am using Spring hibernate.
My code is as below:
String hql = "select a.candidate_id_fk, count(*) from Answers a , Question b where a.question_id_fk = b.id"+""
+"and a.answer=b.correct_answer group by a.candidate_id_fk";
Session session = sessionFactory.getCurrentSession();
List list = session.createQuery(hql).list();
Error:
org.hibernate.hql.internal.ast.ErrorCounter reportError
unexpected token: a
In Eclipselink, when I use #SqlResultSetMappings and I use Query Hint eclipselink.cursor, the console shows me the following exception:
Caused By: java.lang.IllegalArgumentException: Query null, query hint eclipselink.cursor is not valid for this type of query.
at org.eclipse.persistence.internal.jpa.QueryHintsHandler$CursorHint.applyToDatabaseQuery(QueryHintsHandler.java:1640)
at org.eclipse.persistence.internal.jpa.QueryHintsHandler$Hint.apply(QueryHintsHandler.java:367)
at org.eclipse.persistence.internal.jpa.QueryHintsHandler$Hint.apply(QueryHintsHandler.java:345)
at org.eclipse.persistence.internal.jpa.QueryHintsHandler.apply(QueryHintsHandler.java:172)
at org.eclipse.persistence.internal.jpa.QueryImpl.setHintInternal(QueryImpl.java:763)
Truncated. see log file for complete stacktrace
The code is:
#SqlResultSetMapping(
name = "resultSetMapping",
entities = #EntityResult(entityClass = Entity.class))
Query q = em.createNativeQuery(sql, "resultSetMapping";
q.setHint(QueryHints.CURSOR, HintValues.TRUE);
q.getSingleResult();
Why cannot I use SqlResultSetMappings with eclipselink.cursor?
I'm trying to make an update query in HQL, but in doesn't work, I'm using MySQL5Dialect. In Patient class all variables are annotated just like column's names in database. Here is a code:
Controller:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("clinic");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
Patient patient = new Patient();
patient.setFirstName(infonameField.getText());
patient.setLastName(infolastNameField.getText());
patient.setGender(infogenderField.getText());
patient.setAge(infoageField.getText());
patient.setPhonenumber(infophonenumberField.getText());
patient.setAddress(infoadressField.getText());
patient.setDisease(infodiseaseField.getText());
patient.setCondition(infoconditionField.getText());
patient.setRoomtype(infoRoomType.getText());
patient.setRoomNumber(infoRoomNumber.getText());
patient.setDateregistration(infodataField.getText());
patient.setIdpatient(infoPIDField.getText());
Query query = entityManager.createQuery("UPDATE Patient set name = :name, lastname= :lastname,"
+ "gender= :gender, age= :age, phonenumber= :phonenumber, address= :address, disease= :disease,"
+ "condition= :condition, roomtype= :roomtype, roomnumber= :roomnumber, "
+ "dateregistration= :dateregistration WHERE idpatient= :idpatient");
query.setParameter("name", patient.getFirstName());
query.setParameter("lastname", patient.getLastName());
query.setParameter("gender", patient.getGender());
query.setParameter("age", patient.getAge());
query.setParameter("phonenumber", patient.getPhonenumber());
query.setParameter("address", patient.getAddress());
query.setParameter("disease", patient.getDisease());
query.setParameter("condition", patient.getCondition());
query.setParameter("roomtype", patient.getRoomtype());
query.setParameter("roomnumber", patient.getRoomNumber());
query.setParameter("dateregistration", patient.getDateregistration());
query.setParameter("idpatient", patient.getIdpatient());
query.executeUpdate();
entityManager.getTransaction().commit();
Error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition='ewqewqeq', roomtype='standard', roomnumber='101', dateregistration='2' at line 1
The word condition is a keyword in MySQL, probably that's the reason of your error. Try modifying it or replace it by another name.
EDIT
After reading this MySQL forum post, you can use it as long as you escape it, as mentioned here.
I am getting an exception on executing below MySQL query
hibernate dialect used is org.hibernate.dialect.MySQLDialect
following is my simple query.
String queryString= "select action,user_role ,action_desc , action_timestamp, action_done from event_details Where (general_type =1 or disco_type =1 or mask_type =1) and hadoop_type =0 AND COALESCE(source,'Structured') IN ('Both','Structured') and COALESCE(user_id,-1) =1 and Date(action_timestamp) between '2014-01-09' and '2014-04-09' ";
Query query = session.createSQLQuery(queryString);
List list= query = query.list(); ...... This line throws exception.
when same query is executed for count i.e select count(*) from (queryString ) t1;
Then it gets executed fine.
Please suggest what could be the problem ? and how can solve it ??
Problem resolved after adding Scalars to the query.
My question is rather simple: I have this query:
SELECT * FROM TABLE t WHERE
(SELECT count(*) FROM TABLE tbis WHERE TRUNC(t.date) = TRUNC(tbis.date))>1 ;
the field date is a timestamp.
How do I do that with the criteria API?
I have something like this (trunc() is valid with my db server, the sql request works.):
Criteria crit = session.createCriteria(Myclass.class, "t");
crit.createAlias("t.date", "dateT");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.createAlias("tbis.date", "dateTbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC(dateT) = TRUNC(dateTbis)"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
Somehow in the log, i got:
org.hibernate.QueryException: not an association: date
I tried various things, but couldn't get it to work...
I tried:
Criteria crit = session.createCriteria(Myclass.class, "t");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC(t.date) = TRUNC(tbis.date)"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
and the SQL condition generated was:
TRUNC(t.date) = TRUNC(tbis.date))
with the log:
18:34:04,461 WARN [JDBCExceptionReporter] SQL Error: 904, SQLState: 42000
18:34:04,461 ERROR [JDBCExceptionReporter] ORA-00904: "T"."DATE": invalid identifier
18:34:04,461 WARN [CriteriaAdapter] list exception:
org.hibernate.exception.SQLGrammarException: could not execute query
Also
Criteria crit = session.createCriteria(Myclass.class, "t");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC({t}.date) = TRUNC({tbis}.date)"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
with the condition becoming:
TRUNC({t}.date) = TRUNC({tbis}.date))
and the logs:
18:36:28,206 WARN [TxConnectionManager] Connection error occured: org.jboss.resource.connectionmanager.TxConnectionManager$TxConnectionEventListener#1b3febd3[state=NORMAL mc=org.jboss.resource.adapter.jdbc.xa.XAManagedConnection#4cb16baf handles=1 lastUse=1343284588160 permit=true trackByTx=true mcp=org.jboss.resource.connectionmanager.JBossManagedConnectionPool$OnePool#7f16f514 context=org.jboss.resource.connectionmanager.InternalManagedConnectionPool#3c34353b xaResource=org.jboss.resource.adapter.jdbc.xa.XAManagedConnection#4cb16baf txSync=null]
java.lang.NullPointerException
at oracle.jdbc.driver.T4C8Oall.getNumRows(T4C8Oall.java:1153)
[...]
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
Or even:
Criteria crit = session.createCriteria(Myclass.class, "t");
DetachedCriteria subcrit = DetachedCriteria.forclass(MyClass.class, "tbis");
subcrit.add(Restrictions.sqlRestriction("TRUNC({t.date}) = TRUNC({tbis.date})"));
subcrit.setProjection(Projections.count("id"));
crit .add(Subqueries.gt(1, subcrit));
return crit.list();
With the same result as previously.
I think criteria is unable to detect the alias of the subquery... But I have to access that value, any workaround?
First you can try if you shouldn't put the { } only around the alias in the sqlRestriction :
subcrit.add(Restrictions.sqlRestriction("TRUNC({t}.date) = TRUNC({tbis}.date)"));
If you don't want to compare a part of the date fields (like the days), but want to see if the entire date fields are equal, you can just let Hibernate do the comparison like this:
Restrictions.eq(t.date, tbis.date)
If you want to compare a part of a date field, I refer you to this question.