Sometimes and seems randomly Hibernate executes query like that during persist operation:
select currval('MY_TABLE_NAME_id_seq');
Entity:
@Entity
@Table(name = "MY_TABLE_NAME")
public class MyEntity {
@Id
@Column(name = "ID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
}
Code:
@Transactional
public void persistMyEntity(String name) {
MyEntity entity= new MyEntity (name);
sessionFactory.getCurrentSession().persist(entity);
}
Generated sql:
insert into MY_TABLE_NAME(name) values ('xyz');
select currval('MY_TABLE_NAME_id_seq');
But usually select currval is not executed. Is there any explanation about that?
BTW my question is very similar to this but the solution in the question is not worked for me.
Note:
My_TABLE_NAME ddl sql:
CREATE TABLE my_table_name (
id bigserial NOT NULL,
name character varying(256) NOT NULL,
CONSTRAINT my_table_name_id PRIMARY KEY (id)
);
Hibernate properties:
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", "none");
hibernateProperties.put("hibernate.connection.release_mode", "auto");
hibernateProperties.put("hibernate.archive.autodetection", ARCHIVE_AUTODETECTION);
hibernateProperties.put("hibernate.format_sql", true);
hibernateProperties.put("hibernate.use_sql_comments", true);
hibernateProperties.put("hibernate.generate_statistics", false);
hibernateProperties.put("hibernate.jdbc.use_scrollable_resultset", true);
hibernateProperties.put("hibernate.jdbc.use_streams_for_binary", true);
hibernateProperties.put("hibernate.jdbc.batch_size", 20);
hibernateProperties.put("hibernate.order_inserts", true);
hibernateProperties.put("hibernate.order_updates", true);
hibernateProperties.put("hibernate.jdbc.batch_versioned_data ", true);
hibernateProperties.put("hibernate.cache.region_prefix", "hibernate.cache");
hibernateProperties.put("hibernate.cache.use_query_cache", false);
hibernateProperties.put("hibernate.cache.use_second_level_cache", false);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
- PostgreSQL version: 11.5.
- hibernate.dialect:org.hibernate.dialect.PostgreSQL9Dialect
- Hibernate version: 5.4.5.Final
- PostgreSQL JDBC Driver: postgresql-9.4
According to the hibernate documentation:
You can specify
java.sql.Statement#getGeneratedKeysexplicitly in the following way:You do not do it, so, hibernate somehow treat its value as
false. Then hibernate checks value ofdialect.getIdentityColumnSupport().supportsInsertSelectIdentity(). It isfalsefor your case. And then hibernate follows by the last way. See the implementation of the PostgreSQL81IdentityColumnSupport class. The method getIdentitySelectString generates exactly the same sql that you complained about.