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.
Related
JPA repository throwing Error for custom query method:
org.h2.jdbc.JdbcSQLException: Table "NBMRBANKDTLSENTITY" not found; SQL statement:
select NBMRBankDtlsEntity from NBMRBankDtlsEntity where NBMRBankDtlsEntity.ipphId = ? [42102-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
Class :
#Repository
public interface NBMRBankDtlsRepository extends JpaRepository<NBMRBankDtlsEntity, Long> {
#Query(value ="select n from NBMRBankDtlsEntity n where n.ipphId = :ipphId",nativeQuery = true)
Optional<NBMRBankDtlsEntity> findByIPPHId(#Param("ipphId") Long ipphId);
}
The error message tells you: Table "NBMRBANKDTLSENTITY" not found. Therefore it probably doesn't exist. To fix this you'll have to create the table, manually through a script or through hibernates schema creation feature.
I am already creating a table also inserting the record, After that only i am calling this custom query method.
I have found the issue as i am using nativeQuery = true so it is expecting normal sql query to query DB directly not the java query which is creating issue. Now after changing below it works fine ,
#Query(value = "SELECT * from NB_MR_BANK_DTLS WHERE IPPH_ID = :ipphId",nativeQuery = true)
For java query we can use directly as it internally converts to SQL while querying the DB,
#Query(value = "select p from NBMRBankDtlsEntity p WHERE p.ipphId = :ipphId")
Trying to update multiple column values in a table.
What I am missing, a little help!
The dao method is like...
The dao class Plan has all the fields populated with appropriate data.
public void updatePlan(Plan plan) {
SqlParameterSource mapSqlParameterSource = new MapSqlParameterSource().addValue("id", plan.getId())
.addValue("plan_name", plan.getPlan())
.addValue("price_category", plan.getPrice_category())
.addValue("updated_by", subscriptionPlan.getId());
String UPDATE_PLAN = "UPDATE plan_table SET(plan_name= :plan_name, price_category= :price_category, updated_by= :id) where id=:id)";
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(subscriptionPlan);
namedParameterJdbcTemplate.update(UPDATE_PLAN, mapSqlParameterSource);
}
The error is...(MySQL database - 5.6.43, Workbench - 6.3.9)
org.springframework.jdbc.BadSqlGrammarException:
PreparedStatementCallback; bad SQL grammar [update webstat_plan set (plan_name= ?, price_category= ?, updated_by= ?) where id=?)]; nested exception is 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....
Issue is with your SQL Query.
Parenthesis is not required while updating the table.
Update your query with
UPDATE plan_table SET plan_name= :plan_name, price_category= :price_category, updated_by= :id where id=:id
I tried to run native sql query with resulttransformer (AliasToBeanResultTransformer), it gives error like below.
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: com.ozpas.ozentegre.entity.EntDevirlog cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
By the way, my native sql query does not include all fields in the entity ( EntDevirlog ), there are only some fields in that entity. shall the query include all fields in the entity ?
as i understood, hibernate transforms result into a map object instead EntDevirlog entity. It uses PropertyAccessMapImpl. how can i solve this problem to get the result as a list ( arraylist ) ? thanks.
Session session = HibernateUtilMikro.getSessionFactory().openSession();
List<EntDevirlog> results = new ArrayList<EntDevirlog>();
Transaction tx = null;
String sql = "mynativequery";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("tarih", tarih);
query.setParameter("srmkodu", srmkodu);
query.setParameter("s1", EnumPanoislemtipleri.islem1.getValue());
query.setParameter("s2", EnumPanoislemtipleri.islem2.getValue());
query.setResultTransformer(new AliasToBeanResultTransformer(EntDevirlog.class));
results = query.list();
tx.commit();
Just use the quotes for the aliases
"select firstName as \"firstName\",
lastName as \"lastName\" from Employee"
Read for a more deeply explanation here:
mapping Hibernate query results to custom class?
Following is my code snippet:
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/applicationContext*.xml");
JpaTransactionManager jpatm = (JpaTransactionManager) ctx
.getBean("transactionManager");
EntityManager em = jpatm.getEntityManagerFactory()
.createEntityManager();
String sqlQuery = "SELECT suc FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", parentid);
ArrayList<SubUsrCont> listContent = (ArrayList<SubUsrCont>) query.getResultList();
But when ever executed I get the following error:
[http-8080-1] ERROR org.hibernate.hql.PARSER - line 1:92: expecting OPEN, found '.'
Can anybody help???
Well, I found it and successfully tested it as well. It was due to my POJO package name. Previously it was in.myproject.myname. I changed it to com.myproject.myname. HQL was taking in as the SQL Keyword IN and was looking for OPEN '('.
Why are you using a Native SQL query inside em.createQuery()? This will not work because HQL can not have SELECT and furthermore you don't set the value for parameter :parentuserid.
String sqlQuery = "FROM SubUsrCont suc, UDMap uDMap WHERE suc.userid = uDMap.userid AND uDMap.parentuserid = :parentuserid";
TypedQuery<SubUsrCont> query = (TypedQuery<SubUsrCont>) em.createQuery(sqlQuery, SubUsrCont.class);
query.setParameter("parentuserid", <PARENT USER ID TO BE SEARCHED>);
Try this and see
If you would like to execute SQL use createNativeQuery. Also try "SELECT suc.* ...
Also you don't set the parameter :parentuserid
Use query setParameter("parentuserid",someValue)
When I try to execute the following HQL query:
Query query = getSession().createQuery("update XYZ set status = 10");
query.executeUpdate();
I get this exception:
Exception in thread "main" org.hibernate.QueryException: query must begin with SELECT or FROM: update
EDIT:
I also tried following .But it doennot work either.
org.hibernate.Query query = getSession().createQuery("update XYZ t set t.status = 10");
EDIT2:
Making changes in hinbernate.cfg.xml solved my problem
Earlier i was using
setting hibernate.query.factory_class" = org.hibernate.hql.classic.ClassicQueryTranslatorFactor
Now am using following property
<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
Thats not an HQL query.
You want to import javax.persistence.Query which allows normal sql,
not org.hibernate.Query which works on entity objects.
If you want to use simple sql, you could also use PreparedStatement
However, if you really want to use hibernate, without taking advantage of entityobjects (totally defeating the point of using hibernate in the first place, imho) you could do it like this (reference docs):
String myUpdate = "update XYZ myAlias set myAlias.status = :newStatus";
// or String noAliasMyUpdate = "update XYZ set status = :newStatus";
int updatedEntities = getSession().createQuery(myUpdate) //or noAliasMyUpdate
.setInt( "newStatus", 10 )
.executeUpdate();
The question is thinking in SQL, when you should be thinking in objects:
XYZ xyz = new XYZ();
xyz.setStatus(10);
getSession().merge(xyz);
Try:
Query query = getSession().createQuery("update XYZ o set o.status = 10");
query.executeUpdate();
Take a look at this also.
Session sesssion = getSession(); //getter for session
For HQL :
String hql = "update Activity " +
"set startedOn = :taskStartedOn " +
"where id = :taskId";
Query query = session.createQuery(hql);
query.setDate("taskStartedOn",new Date());
query.setLong("taskId",1)
int rowCount = query.executeUpdate();
Here Activity is POJO.
Use
hibernate.query.factory_class = org.hibernate.hql.ast.ASTQueryTranslatorFactory
in hibernate.cfg.xml file to resolve exception:
org.hibernate.QueryException: query must begin with SELECT or FROM: update.....