With Hibernate, I am trying to execute a query by setting multiple values from list and executing it at the same time. Here is the code
public void savePriority(List<Integer> priorities,int typeid) {
String sql="update table conf_sr_type_baserule_assoc set n_priority=:priority where n_typeid=:typeid";
/*System.out.println("sql query in savePriority"+sql);*/
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
SQLQuery squery=session.createSQLQuery(sql);
tx.begin();
for(int priority:priorities){
squery.setParameter("priority", priority);
squery.setParameter("typeid", typeid);
squery.executeUpdate();
}
tx.commit();
session.close();
}
but I am getting an error:
org.hibernate.exception.SQLGrammarException: could not execute native bulk manipulation query
The problem comes from your SQL query, which is invalid.
It should be:
update conf_sr_type_baserule_assoc set n_priority=:priority where n_typeid=:typeid
instead of
update table conf_sr_type_baserule_assoc set n_priority=:priority where n_typeid=:typeid
Related
I am insert data in db is good. The problem is after inserted data i am trying to get last inserted data primary key column. But i can't how to solve this problem.
note : i am using jpql , Thanks
public void insertData(String hcpHceId) {
EntityManager em = getEntityManager();
em.getTransaction().begin();
// Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(:id)" );
Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(?)");
query.setParameter(1, hcpHceId);
query.executeUpdate(); // Successfully inserted data
List list = query.setMaxResults(1).getResultList(); // Error line
em.getTransaction().commit();
} catch (Exception error) {
error.printStackTrace();
logger.error(error.getMessage());
} finally {
em.close();;
}
}
You are trying to retrieve the list from the same execute query. Query is an immutable object. You must create a new query with the proper select statement, so you will be able to retrieve data from database.
After the executeUpdate, create the new query using, v.g. (as you did not show your entity graph, using native sql):
Query retQuery = em.createNativeQuery("SELECT hcp_hce_id FROM mdm_id LIMIT 1");
String id = (String) retQuery.getSingleResult();
assert(id == hcpHceId);
I have a rest api Spring MVC,database oracle sql developer and I am using hibernate for mapping.
I have a table Iteration.My code is:
#RequestMapping(value="{userid}",method=RequestMethod.GET)
public #ResponseBody List<IterationInfo> getIterationInfoInJSON(#PathVariable int userid)
{
Configuration con = new Configuration();
con.configure("hibernate.cfg.xml");
SessionFactory SF = con.buildSessionFactory();
Session session= SF.openSession();
Transaction TR = session.beginTransaction();
Query query=session.createQuery("from IterationInfo");
List<IterationInfo> listiterationinfo=query.list();
session.close();
SF.close();
return listiterationinfo;
}
I want to fire a query select * from IterationInfo where userid=(The userid I get from the path variable).
Like from (#pathVariable int userid)
What query should I use in my class??
Query query=session.createQuery("from IterationInfo WHERE userId=:userId");
query.setParameter("userId", userid);
IterationInfo iterationinfo=query.uniqueResult(); // Returns null if not found
I cannot see your IterationInfo class, so I'm not 100% sure on the name of the field there (I assumed userId).
Try this this may help you.
String hql = "from iterationInfo WHERE userId=:userId";
Query query = session.createQuery(hql);
query.setParameter("userId", userid);
List<IterationInfo> iterationinfolist = query.list();
I would like to ask you for help with following problem. I have method:
String sql = "INSERT INTO table ...."
Query query = em.createNativeQuery(sql);
query.executeUpdate();
sql = "SELECT max(id) FROM ......";
query = em.createNativeQuery(sql);
Integer importId = ((BigDecimal) query.getSingleResult()).intValue();
for (EndurDealItem item : deal.getItems()) {
String sql2 = "INSERT INTO another_table";
em.createNativeQuery(sql2).executeUpdate();
}
And after executing it, data are not commited (it takes like 10 or 15 minutes until data are commited). Is there any way how to commit data explicitly or trigger commit? And what causes the transaction to remain uncommited for such a long time?
The reason we use nativeQueries is, that we are exporting data on some shared interface and we are not using the data anymore.
I would like to mention, that the transaction is Container-Managed (by Geronimo). EntityManager is created via linking:
#PersistenceContext(unitName = "XXXX", type = PersistenceContextType.TRANSACTION)
private EntityManager em;
Use explicitly the transaction commit:
EntityManager em = /* get an entity manager */;
em.getTransaction().begin();
// make some changes
em.getTransaction().commit();
This should work. The time of execution of all operation between .begin() and .end() depends of course also from the cycle you're performing, the number of row you're inserting, from the position of the database (the speed of the network matters) and so on...
I'm trying to fetch the last entity that was inserted into the database, which I thought would be a very simple thing to do, but every query i try results in some sort of exception to get thrown
The code im using is:
#Override
public DataStoreMark getLastMark() {
String selectQuery = "from Mark";
Query query = em.createNativeQuery(selectQuery, DataStoreMark.class);
try {
return (DataStoreMark) query.getSingleResult();
} catch (NoResultException e) {
log.error("Couldn't find any Marks in the DataStore.");
}
return null;
}
This code however throws a PesistenceException:
org.hibernate.exception.SQLGrammarException: 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 'from milestone' at line 1
And there is definitely a record in the database.
Any ideas?
You can use either of createQuery() and createSqlQuery() if it does not work:
1.
String selectQuery = "from Mark";
Query query = em.createQuery(selectQuery);
return (DataStoreMark) query.list().get(0);
2.
String selectQuery = "select * from Mark";
SQLQuery query = (SQLQuery) em.createSQLQuery(selectQuery);
query.addEntity(DataStoreMark.class);
return query.list();
I think hibernate does not tell about last entity added to the database. Alternatively you can write the query specific to your db and run it using createSqlQuery() as shown above.
I have just set up a test that checks that I am able to insert entries into my database using Hibernate. The thing that drives me crazy is that Hibernate does not actually delete the entries, although it reports that they are gone!
The test below runs successfully, but when I check my DB afterwards the entries that were inserted are still there! I even try to check it using assert (yes I have -ea as vm parameter). Does anyone have a clue why the entries are not deleted?
public class HibernateExportStatisticDaoIntegrationTest {
HibernateExportStatisticDao dao;
Transaction transaction;
#Before
public void setUp(){
assert numberOfStatisticRowsInDB() == 0;
dao = new HibernateExportStatisticDao(HibernateUtil.getSessionFactory());
}
#After
public void deleteAllEntries(){
assert numberOfStatisticRowsInDB() != 0;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
for(PersistableStatisticItem item:allStatisticItemsInDB()) {
session.delete(item);
}
session.flush();
assert numberOfStatisticRowsInDB() == 0;
}
#Test public void exportAllSavesEntriesToDatabase(){
int expectedNumberOfStatistics = 20;
dao.exportAll(StatisticItemFactory.createTestStatistics(expectedNumberOfStatistics));
assertEquals(expectedNumberOfStatistics, numberOfStatisticRowsInDB());
}
private int numberOfStatisticRowsInDB() {
return allStatisticItemsInDB().size();
}
#SuppressWarnings("unchecked")
private List<PersistableStatisticItem> allStatisticItemsInDB(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
transaction = session.beginTransaction();
Query q = session.createQuery("FROM PersistableStatisticItem item");
return q.list();
}
}
The console is filled with
Hibernate: delete from UPTIME_STATISTICS where logDate=? and serviceId=?
but nothing has been deleted when I check it.
I guess it's related to inconsistent use of transactions (note that beginTransaction() in allStatisticItemsInDB() is called several times without corresponding commits).
Try to manage transactions in proper way, for example, like this:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
for(PersistableStatisticItem item:
session.createQuery("FROM PersistableStatisticItem item").list()) {
session.delete(item);
}
session.flush();
assert session.createQuery("FROM PersistableStatisticItem item").list().size() == 0;
tx.commit();
See also:
13.2. Database transaction demarcation
I have the same problem. Although I was not using transaction at all. I was using namedQuery like this :
Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
session.close();
It was returning 2 rows but the database still had all the records. Then I wrap up the above code with this :
Transaction transaction = session.beginTransaction();
Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES);
int rows = query.executeUpdate();
transaction.commit();
session.close();
Then it started working fine. I was using SQL server. But I think if we use h2, above code (without transaction) will also work fine.
One more observation : To insert and get records usage of transaction is not mandatory but for deletion of records we will have to use transaction. (only tested in SQL server)
Can you post your DB schema and HBM or Fluent maps? One thing that got me a while back was I had a ReadOnly() in my Fluent map. It never threw an error and I too saw the "delete from blah where blahblah=..." in the logs.