我现在正面临一个让我抓狂的问题。
我想创建自己的IdentifierGenerator来管理特定格式的ID。
public class CustomGenerator implements IdentifierGenerator {
private static final String REQUEST = "SELECT CURRVAL('sequence')";
private final String prefixFormat = "PREFIX-%s";
@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
final String prefix = getPrefix();
Session sessionHibernate = (Session) session;
Query query = sessionHibernate.createSQLQuery(REQUEST );
Object obj = query.uniqueResult();
return null;
}
private String getPrefix() {
final Calendar date = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
return String.format(prefixFormat, dateFormat.format(date.getTime()));
}
}
我的Junit测试:
@Test
@Transactional
public void addEntity() {
final Entity entity= new Entity();
final long count = this.entityRepository.count();
this.entityRepository.saveAndFlush(rex);
assertEquals(count + 1, this.entityRepository.count());
}
我的实体:
@Entity
@Table(name = "ENTITY")
public class Entity {
@Id
@GenericGenerator(name = "sequence", strategy = "[...]CustomGenerator")
@GeneratedValue(generator = "sequence")
@Column(name = "ENTITY_ID")
private Integer entityId;
[...]
}
我的JUnit测试崩溃- Stacktrace:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [SELECT CURRVAL('sequence_rex_id')]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:238)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
数据库:HSQLDB(测试)、POSTGRESQL(生产)
有人知道吗?
对于我可能犯的任何错误,我感到抱歉。英语不是我的母语。
2条答案
按热度按时间mf98qq941#
SELECT CURRVAL('sequence')
语法特定于PostgreSQL。在HSQLDB中使用PostgreSQL语法时,应在JDBC连接URL中包含必要的SQL语法标志。例如jdbc:hsqldb:mem:test;sql.syntax_pgs=true
9udxz4iz2#
您需要使用
nextval
而不是CURRVAL
。是
返回nextval在当前会话中为该序列最近获得的值。(如果nextval在该会话中从未被调用,则报告错误。**)(https://www.postgresql.org/docs/current/functions-sequence.html)