@SuppressWarnings("unchecked") @Transactional public String addTrainingTest() { org.hibernate.Query query = hibernateTemplate .getSessionFactory() .getCurrentSession() .createSQLQuery( "SELECT CONCAT('train', LPAD(SUBSTR(`id`, 6) + 1, 5, '0')) `next_id` " + "FROM `test_executions` WHERE `id` LIKE 'train%' ORDER BY " + "SUBSTR(`id`, 6) + 0 DESC LIMIT 1") .addScalar("next_id", Hibernate.STRING); hibernateTemplate.setMaxResults(1); List<String> l = query.list(); hibernateTemplate.setMaxResults(0); String nextId = l.size() > 0 ? l.get(0) : null; TestExecution t = new TestExecution(); t.setId(nextId); t.setTestId(1); this.saveTestExecution(t); return nextId; }