Select last entity inserted with hibernate - java

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.

Related

Sqlite-JDBC update with LIMIT clause?

I am trying to use the update query with the LIMIT clause using sqlite-JDBC.
Let's say there are 100 bob's in the table but I only want to update one of the records.
Sample code:
String name1 = "bob";
String name2 = "alice";
String updateSql = "update mytable set user = :name1 " +
"where user is :name2 " +
"limit 1";
try (Connection con = sql2o.open()) {
con.createQuery(updateSql)
.addParameter("bob", name1)
.addParameter("alice", name2)
.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
I get an error:
org.sql2o.Sql2oException: Error preparing statement - [SQLITE_ERROR] SQL error or missing database (near "limit": syntax error)
Using
sqlite-jdbc 3.31
sql2o 1.6 (easy database query library)
The flag:
SQLITE_ENABLE_UPDATE_DELETE_LIMIT
needs to be set to get the limit clause to work with the update query.
I know the SELECT method works with the LIMIT clause but I would need 2 queries to do this task; SELECT then UPDATE.
If there is no way to get LIMIT to work with UPDATE then I will just use the slightly more messy method of having a query and sub query to get things to work.
Maybe there is a way to get sqlite-JDBC to use an external sqlite engine outside of the integrated one, which has been compiled with the flag set.
Any help appreciated.
You can try this query instead:
UPDATE mytable SET user = :name1
WHERE ROWID = (SELECT MIN(ROWID)
FROM mytable
WHERE user = :name2);
ROWID is a special column available in all tables (unless you use WITHOUT ROWID)

javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Can not issue data manipulation statements with executeQuery()

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);

Getting an error while using "Generics" in Hibernate Query

I'm using Hibernate in my project and using "Query" Like below.
Query query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
I'm getting the result. When i'm using generics Like below
Query<?> query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
getting the result because "?" is something as wildcard (or) it will accept any datatype
when i'm using the code as below getting some error( java.lang.IllegalArgumentException: Update/delete queries cannot be typed ). i'm using Integer datatype because createQuery return number when it's executed
Query<Integer> query = em.createQuery("delete from User where name=:name", Integer.class);
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
Any suggestions. I have to use Generics with specific datatype in it like above code.
thanks in advance
Unfortunately executeUpdate does not allow you to use a typed query.
Instead you can use uniqueResult, and cast to the type that you want:
Query query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = (Integer) query.uniqueResult();
Referencing this answer

Java native query - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I get following error: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Card.findPrefix'"
for:
#NamedNativeQueries({
#NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c
.number/10000)) FROM Card c")
})
public List<Integer> findPrefix(){
Query q = em.createNativeQuery("Card.findPrefix");
try{
return q.getResultList();
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
I can not understand where is my mistake, because when I type this query directly to Mysql it works perfectly.
Use should use createNamedQuery, instead of createNativeQuery.
From EntityManager JavaDoc
createNativeQuery(String sqlString)
Create an instance of Query for executing a native SQL statement, e.g., for update or delete.
createNamedQuery(String name)
Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).
So in your code you are executing query name 'Find....' as SQL query.
The right one:
Query q = em.createNamedQuery("Card.findPrefix");
Final code is:
public List<Integer> findPrefix(){
Query q = em.createNamedQuery("Card.findPrefix");
List<Integer> res = new ArrayList<Integer>();
for(Object row : (List<Object>) q.getResultList()){
res.add(((BigInteger)row).intValue());
}
return res;
}
#NamedNativeQueries({
#NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c.number/10000)) FROM Card c")
})

createSQLQuery in Hibernate

I have the following code:
String SQL_QUERY ="Select abstractDesc from article";
Query query = session.createSQLQuery(SQL_QUERY);
Object [] amount = (Object []) query.uniqueResult();
out.println("mean amount: " + amount[0]);
but I get the following error:
Hibernate: Select abstractDesc from article
query did not return a unique result: 10
How can I solve this to have the query executed and print the result properly?
As you are using uniqueResult(), you are telling Hibernate that you are expecting only a single value.
Check your database or replace uniqueResult() with [list()]1 to see what you get back.

Categories

Resources