我需要一种方法来获取数据库中实体的最后一个id,例如
产品实体:
我试试这个,但它不起作用:
public int lastInsertedId() {
try {
if (!session.isOpen())
session = DatabaseUtil.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createSQLQuery("select last_value from purchase_idpurchase_seq ");
int lastid = query.getFirstResult();
session.getTransaction().commit();
session.close();
return lastid;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
答案 0 :(得分:1)
经过一段谷歌搜索后,我得到了解决方案:
public int lastInsertedId() {
try {
if (!session.isOpen())
session = DatabaseUtil.getSessionFactory().openSession();
session.beginTransaction();
Criteria c = session.createCriteria(Purchase.class);
c.addOrder(Order.desc("id"));
c.setMaxResults(1);
int id = (int) ((Purchase) c.uniqueResult()).getIdPurchase();
session.getTransaction().commit();
session.close();
return id;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
答案 1 :(得分:0)
尝试使用以下内容:
String hql = "from purchase_idpurchase_seq";
Query query = session.createQuery(hql);
List<purchase_idpurchase_seq> results = query.list();
要获得last_value
的值,请尝试以下操作:
String last_value = results.getLast_value(); // if getLast_value return int use int.
我想你有一个实体purchase_idpurchase_seq
尝试查看此site