Could not prepare statement while saving via entity manager - java

I've got the following error:
07:27:02,736 INFO Version:37 - HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
07:27:02,745 INFO Version:41 - HHH000412: Hibernate Core {4.2.0.Final}
07:27:02,755 INFO Environment:239 - HHH000206: hibernate.properties not found
07:27:02,757 INFO Environment:342 - HHH000021: Bytecode provider name : javassist
07:27:02,799 INFO Configuration:1933 - HHH000043: Configuring from resource: ./hibernate.cfg.xml
07:27:02,799 INFO Configuration:1952 - HHH000040: Configuration resource: ./hibernate.cfg.xml
07:27:02,888 WARN DTDEntityResolver:74 - HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
07:27:02,960 INFO Configuration:2074 - HHH000041: Configured SessionFactory: null
07:27:03,677 INFO DriverManagerConnectionProviderImpl:98 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
07:27:03,712 INFO DriverManagerConnectionProviderImpl:134 - HHH000115: Hibernate connection pool size: 20
07:27:03,713 INFO DriverManagerConnectionProviderImpl:137 - HHH000006: Autocommit mode: false
07:27:03,713 INFO DriverManagerConnectionProviderImpl:151 - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/ForBook]
07:27:03,713 INFO DriverManagerConnectionProviderImpl:156 - HHH000046: Connection properties: {user=root, password=****}
07:27:05,539 INFO Dialect:128 - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
07:27:05,570 INFO LobCreatorBuilder:94 - HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
07:27:05,608 INFO TransactionFactoryInitiator:68 - HHH000399: Using default transaction strategy (direct JDBC transactions)
07:27:05,633 INFO ASTQueryTranslatorFactory:48 - HHH000397: Using ASTQueryTranslatorFactory
07:27:05,822 INFO Version:39 - HSEARCH000034: Hibernate Search 4.3.0.Alpha1
07:27:05,988 WARN ConfigContext:301 - HSEARCH000075: Configuration setting hibernate.search.lucene_version was not specified, using LUCENE_CURRENT.
07:27:06,703 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
07:27:06,704 DEBUG SchemaExport:353 - Import file not found: /import.sql
07:27:06,706 DEBUG SQL:104 - alter table BEE drop foreign key FK100622C0E7E16
07:27:07,463 DEBUG SQL:104 - drop table if exists BEE
07:27:07,829 DEBUG SQL:104 - drop table if exists HONEY
07:27:07,999 DEBUG SQL:104 - create table BEE (id integer not null auto_increment, city varchar(255), street varchar(255), myEnum varchar(255), nameOfBee varchar(255), honey_id integer not null, primary key (id))
07:27:08,533 DEBUG SQL:104 - create table HONEY (honey_id integer not null auto_increment, NAME_OF_HONEY varchar(255), taste varchar(255), primary key (honey_id))
07:27:08,955 DEBUG SQL:104 - alter table BEE add index FK100622C0E7E16 (honey_id), add constraint FK100622C0E7E16 foreign key (honey_id) references HONEY (honey_id)
07:27:10,344 INFO SchemaExport:405 - HHH000230: Schema export complete
07:27:10,667 INFO DriverManagerConnectionProviderImpl:98 - HHH000402: Using Hibernate built-in connection pool (not for production use!)
07:27:10,680 INFO DriverManagerConnectionProviderImpl:134 - HHH000115: Hibernate connection pool size: 20
07:27:10,681 INFO DriverManagerConnectionProviderImpl:137 - HHH000006: Autocommit mode: true
07:27:10,681 INFO DriverManagerConnectionProviderImpl:151 - HHH000401: using driver [org.hsqldb.jdbcDriver] at URL [jdbc:hsqldb:.]
07:27:10,681 INFO DriverManagerConnectionProviderImpl:156 - HHH000046: Connection properties: {user=sa, password=****, autocommit=true, release_mode=auto}
07:27:10,907 INFO Dialect:128 - HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
07:27:10,909 INFO LobCreatorBuilder:94 - HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
07:27:10,910 INFO TransactionFactoryInitiator:73 - HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
07:27:10,910 INFO ASTQueryTranslatorFactory:48 - HHH000397: Using ASTQueryTranslatorFactory
07:27:10,924 WARN ConfigContext:301 - HSEARCH000075: Configuration setting hibernate.search.lucene_version was not specified, using LUCENE_CURRENT.
07:27:10,947 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
07:27:10,948 DEBUG SchemaExport:353 - Import file not found: /import.sql
07:27:10,948 DEBUG SQL:104 - alter table BEE drop constraint FK100622C0E7E16
07:27:10,950 ERROR SchemaExport:425 - HHH000389: Unsuccessful: alter table BEE drop constraint FK100622C0E7E16
07:27:10,950 ERROR SchemaExport:426 - Table not found: BEE in statement [alter table BEE]
07:27:10,950 DEBUG SQL:104 - drop table BEE if exists
07:27:10,951 DEBUG SQL:104 - drop table HONEY if exists
07:27:10,951 DEBUG SQL:104 - create table BEE (id integer generated by default as identity (start with 1), city varchar(255), street varchar(255), myEnum varchar(255), nameOfBee varchar(255), honey_id integer not null, primary key (id))
07:27:10,953 DEBUG SQL:104 - create table HONEY (honey_id integer generated by default as identity (start with 1), NAME_OF_HONEY varchar(255), taste varchar(255), primary key (honey_id))
07:27:10,953 DEBUG SQL:104 - alter table BEE add constraint FK100622C0E7E16 foreign key (honey_id) references HONEY
07:27:10,956 INFO SchemaExport:405 - HHH000230: Schema export complete
07:27:11,190 DEBUG SQL:104 - insert into HONEY (honey_id, NAME_OF_HONEY, taste) values (null, ?, ?)
07:27:11,191 WARN SqlExceptionHelper:143 - SQL Error: -20, SQLState: IM001
07:27:11,191 ERROR SqlExceptionHelper:144 - This function is not supported
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1316)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:881)
at ua.hibernate_project.TestWork.main(TestWork.java:88)
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:188)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:117)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:55)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2966)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3477)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:203)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:183)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:167)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:321)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:78)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:852)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:826)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:830)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:875)
... 1 more
Caused by: java.sql.SQLException: This function is not supported
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.Util.notSupported(Unknown Source)
at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$2.doPrepare(StatementPreparerImpl.java:119)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
... 22 more
While I try to work with entity manager (via Hibernate API all works good)
I can see entity manager tries to insert id, i.e. honey_id
DEBUG SQL:104 - insert into HONEY (honey_id, NAME_OF_HONEY, taste) values (null, ?, ?)
via Hibernate API I see follow
DEBUG SQL:104 - insert into HONEY (NAME_OF_HONEY, taste) values (?, ?)
My classes
Bee:
#Entity
#Table(name = "BEE")
public class Bee {
#ManyToOne
#JoinColumn(name = "honey_id", nullable = false)
private Honey honey;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nameOfBee;
#Enumerated(EnumType.STRING)
private MyEnum myEnum = MyEnum.UNNORMAL;
#Embedded
private Address address;
Honey:
#Table(name = "HONEY")
#Entity
public class Honey {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "honey_id")
private int id;
#Column(name = "NAME_OF_HONEY")
private String nameOfHoney;
private String taste;
#OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, mappedBy = "honey" )
private Set<Bee> bees;
Address:
#Embeddable
public class Address {
public Address() {}
TestWork:
public class TestWork {
private static SessionFactory sessionFactory;
private static EntityManagerFactory emf;
private Session session;
static{
Configuration configuration = new Configuration();
configuration.configure("./hibernate.cfg.xml");
ServiceRegistryBuilder serviceRegistryBuilder =
new ServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
emf = Persistence.createEntityManagerFactory("hibernate-search-example");
}
public Session openSessionAndGetTransaction(){
session = sessionFactory.openSession();
session.getTransaction().begin();
return session;
}
public static EntityManager getEntityManager(){
return emf.createEntityManager();
}
public void commitAndCloseSession(){
session.getTransaction().commit();
session.close();
}
public static void main(String[] args) {
TestWork testWork = new TestWork();
EntityManager em = TestWork.getEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Address address = new Address("Dnipro", "K.Marksa");
Honey honeyFromForest = new Honey("FirstHoney","Very tasty");
Bee firstBee = new Bee();
firstBee.setAddress(address);
firstBee.setNameOfBee("I'm first Bee");
firstBee.setHoney(honeyFromForest);
Bee secondBee = new Bee();
secondBee.setAddress(address);
secondBee.setNameOfBee("I'm second Bee");
secondBee.setHoney(honeyFromForest);
Set<Bee> bees = new HashSet<Bee>();
bees.add(firstBee);
bees.add(secondBee);
honeyFromForest.setBees(bees);
em.persist(honeyFromForest);
em.persist(firstBee);
em.persist(secondBee);
}
Thank you for your help!

Related

In Hibernate using update but still going for a create table

Using Hibernate in my project. I am getting create table queries at my logs,
But I am using a HBM2DDL_AUTO="update"
What else could had been missed ?
PS: I get these logs only when the tables are already present at runtime. If tables not present, it obviously runs smooth.
Here are the properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.postgresql.Driver");
settings.put(Environment.URL, "jdbc:postgresql://" + jdbc_host + ":5432/" + jdbc_database + "?prepareThreshold=0");
settings.put(Environment.USER, jdbc_user);
settings.put(Environment.PASS, jdbc_password);
settings.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "update");
Error Logs:
[INFO ]: org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
[INFO ]: org.hibernate.type.BasicTypeRegistry - HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#3add81c4
[WARN ]: org.hibernate.boot.internal.InFlightMetadataCollectorImpl - HHH000069: Duplicate generator name wca_seq_generator
[WARN ]: org.hibernate.boot.internal.InFlightMetadataCollectorImpl - HHH000069: Duplicate generator name wca_seq_generator
[WARN ]: org.hibernate.boot.internal.InFlightMetadataCollectorImpl - HHH000069: Duplicate generator name wca_seq_generator
[INFO ]: org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#59696551] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
[WARN ]: org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl - GenerationTarget encountered exception accepting command : Error executing DDL "create table WCA_MESSAGE_AUDIT (id int8 not null, createts times
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table WCA_MESSAGE_AUDIT (id int8 not null, create
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
I have not worked postgresql in java but I've worked with MySQL. And Whenever' I need to create the table using hibernate then I mention the follow feature in application.properties and it allow to create the table. please once go for it and if it still doesn't work please inform me. Put it in proprerties.
spring.jpa.hibernate.ddl-auto=update

Hibernate creating table but not creating entry?

I am trying to test that my connection to Hibernate is working in my code so I set up a basic method to create a new entity in a table. When I run the code I don't see an error and when I first ran it Hibernate successfully created the table but the row is not being created in the table. Anyone know why this might be happening? Pasted User class and code to create below as well as logs.
public static void main(String[] args) {
Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = new User();
user.setPassword("abcd");
user.setStatus(UserStatus.OFFLINE);
user.setUserName("testuser");
session.save(user);
}
User class:
#Entity
#Table(name="USERS")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="USER_ID")
private String userId;
#Column(name="USER_NAME")
private String userName;
#Column(name="PASSWORD")
private String password;
#Enumerated(EnumType.STRING)
#Column(name="STATUS")
private UserStatus status;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
}
Logs:
[main] INFO org.hibernate.cfg.Environment - Hibernate 3.5.1-Final
[main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
[main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
[main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
[main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
[main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
[main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : messagingservice/db/User.hbm.xml
[main] INFO org.hibernate.cfg.HbmBinder - Mapping class: messagingservice.db.User -> USERS
[main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
[main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
[main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
[main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
[main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/CAREZONE_MESSAGING
[main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=hibernate, password=****}
[main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.7.11-log
[main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL Connector Java, version: mysql-connector-java-5.1.37 ( Revision: 09940f05b4c98150f352e787a2549f11a2e9da93 )
[main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
[main] INFO org.hibernate.transaction.TransactionFactoryFactory - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
[main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
[main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
[main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
[main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
[main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
[main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
[main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
[main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
[main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
[main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
[main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
[main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
[main] INFO org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge - Cache provider: org.hibernate.cache.HashtableCacheProvider
[main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
[main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
[main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
[main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
[main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
[main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
[main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - Running hbm2ddl schema export
[main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - exporting generated schema to database
[main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - schema export complete
You are not committing your transaction. You need to do:
public static void main(String[] args) {
Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setPassword("abcd");
user.setStatus(UserStatus.OFFLINE);
user.setUserName("testuser");
session.save(user);
tx.commit();
session.close();
}

Entity not being persisted when using jpa

I am using the following field annotations:
#Id
#TableGenerator( name = "comment_sequence", pkColumnValue = "comment_sequence" )
#GeneratedValue( strategy = GenerationType.TABLE, generator = "comment_sequence" )
private Long id_comment;
The sql for creating the table is:
CREATE TABLE hibernate_sequences ( sequence_name VARCHAR(255) NOT NULL, next_val bigint, PRIMARY KEY ( sequence_name ) );
INSERT INTO hibernate_sequences VALUES ( 'comment_sequence', 1 );
But the entity simply is not persisting. Any idea of what could be happening? Am I doing something wrong with the code presented above?
EDIT:
I suppressed a few information in the original post, I'm sorry (asked in the middle of night almost sleeping =/).
The entity is being properly created, if I do change the strategy to SEQUENCE and add the SQL CREATE SEQUENCE hibernate_sequence everything works fine (it is persisted), but I want to use the TABLE strategy to hold each table sequence in a row on hibernate_sequences.
The only exceptions I have is the TransactionRolledbackException due to a NullPointerException caused by a failing test in the integration test. Nothing explicit for why it is not inserting the data.
I get the following hibernate output when using hibernate.show_sql = true:
...
12:38:48,753 INFO [stdout] (pool-5-thread-1) Hibernate:
12:38:48,754 INFO [stdout] (pool-5-thread-1) insert
12:38:48,755 INFO [stdout] (pool-5-thread-1) into
12:38:48,756 INFO [stdout] (pool-5-thread-1) cm_comment
12:38:48,757 INFO [stdout] (pool-5-thread-1) (cd_status, ds_message, dt_alt, dt_inc, id_user_alt, id_user_inc, id_problem, id_comment)
12:38:48,758 INFO [stdout] (pool-5-thread-1) values
12:38:48,759 INFO [stdout] (pool-5-thread-1) (?, ?, ?, ?, ?, ?, ?, ?)
12:38:48,766 INFO [stdout] (pool-5-thread-1) Hibernate:
12:38:48,766 INFO [stdout] (pool-5-thread-1) select
12:38:48,767 INFO [stdout] (pool-5-thread-1) commentent0_.id_comment as id1_6_,
12:38:48,768 INFO [stdout] (pool-5-thread-1) commentent0_.cd_status as cd2_6_,
12:38:48,770 INFO [stdout] (pool-5-thread-1) commentent0_.ds_message as ds3_6_,
12:38:48,771 INFO [stdout] (pool-5-thread-1) commentent0_.dt_alt as dt4_6_,
12:38:48,772 INFO [stdout] (pool-5-thread-1) commentent0_.dt_inc as dt5_6_,
12:38:48,773 INFO [stdout] (pool-5-thread-1) commentent0_.id_user_alt as id6_6_,
12:38:48,774 INFO [stdout] (pool-5-thread-1) commentent0_.id_user_inc as id7_6_,
12:38:48,775 INFO [stdout] (pool-5-thread-1) commentent0_.id_problem as id8_6_
12:38:48,776 INFO [stdout] (pool-5-thread-1) from
12:38:48,777 INFO [stdout] (pool-5-thread-1) cm_comment commentent0_
12:38:48,778 INFO [stdout] (pool-5-thread-1) where
12:38:48,779 INFO [stdout] (pool-5-thread-1) commentent0_.id_problem=?
12:38:48,840 ERROR [org.jboss.arquillian.protocol.jmx.JMXTestRunner] (pool-5-thread-1)
...
java.lang.AssertionError: expected:<1> but was:<0>
...
I am not sure if this can be related but in a previous test I get the error:
12:50:36,510 INFO [org.jboss.as.ejb3] (pool-4-thread-1) JBAS014101: Failed to find SFSB instance with session ID {[-98, -17, -32, -33, 63, 107, 74, 59, -76, -127, -19, 29, 24, 45, -50, 5]} in cache
When I change postgresql.conf for log_statement = 'all' and check in the pg_log directory after running the app I dont see any logs. So I am not sure how I can enable that option.
I am also using Arquillian, arquillian persistence API, and a JBoss managed instance for integration testing. I am going to update the tags cause this could be related to any of those.
Your "declaration" of TableGenerator isn't given any info about which table it should look in / use, all you're giving it is a pkColumn name ....
Try:
#TableGenerator(
name = "comment_sequence",
table = "hibernate_sequences",
pkColumnName = "sequence_name",
valueColumnName = "next_val",
pkColumnValue = "comment_sequence",
allocationSize=1)
allocationSize=1 should probably be something larger than 1 ... when you've verified it is working.
(Down the line, be aware of potential locking problems if you use this strategy and put a lot of generators into the same table in the db - if you're application is creating "lots of" entities.)

Partial schema export in hibernate

Hibernate version 3.6
I am trying to do a partial schema export using hbm2dll SchemaExport. Therefore I access the current hibernate configuration, retrieve the PersistentClass the table shall be generated for and create a new configuration as follows:
ClassMetadata classMetadata = sessionFactory.getClassMetadata(SchemaVersion.class);
String entityName = classMetadata.getEntityName();
PersistentClass persistentClass = origCfg.getClassMapping(entityName);
final Configuration cfg = new Configuration();
Properties properties = origCfg.getProperties();
cfg.setProperties(properties);
cfg.createMappings().addClass(persistentClass);
cfg.buildMappings();
Iterator<PersistentClass> mappings = cfg.getClassMappings();
System.out.println("=========== MAPPINGS ===================");
while (mappings.hasNext()) {
PersistentClass pClass = mappings.next();
System.out.println(pClass.getClassName());
System.out.println(pClass.getTable().getName());
}
System.out.println("=========== END MAPPINGS ===============");
Session session = sessionFactory.openSession();
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
new SchemaExport(cfg, connection).create(true, true);
}
});
session.close();
As it is visible from the log (below) the schema export seems to complete but it looks like it is not picking up the programmaticly added mapping since the table is not created.
=========== MAPPINGS ===================
eu.codecamp.utils.lib.persistence.schema.SchemaVersion
fx_schema_version
=========== END MAPPINGS ===============
DEBUG: opened session at timestamp: 5387886841208832 - 2011-09-07 15:27:40,842 [org.hibernate.impl.SessionImpl]
DEBUG: opening JDBC connection - 2011-09-07 15:27:40,843 [org.hibernate.jdbc.ConnectionManager]
INFO: Using dialect: org.hibernate.dialect.MySQLInnoDBDialect - 2011-09-07 15:27:40,885 [org.hibernate.dialect.Dialect]
DEBUG: Processing hbm.xml files - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: Process annotated classes - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: processing fk mappings (*ToOne and JoinedSubclass) - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: processing extends queue - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: processing extends queue - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: processing collection mappings - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: processing native query and ResultSetMapping mappings - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: processing association property references - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: processing foreign key constraints - 2011-09-07 15:27:40,885 [org.hibernate.cfg.Configuration]
DEBUG: Setting dialect [org.hibernate.dialect.MySQLInnoDBDialect] - 2011-09-07 15:27:40,887 [org.hibernate.id.factory.DefaultIdentifierGeneratorFactory]
DEBUG: Processing hbm.xml files - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: Process annotated classes - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: processing fk mappings (*ToOne and JoinedSubclass) - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: processing extends queue - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: processing extends queue - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: processing collection mappings - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: processing native query and ResultSetMapping mappings - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: processing association property references - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: processing foreign key constraints - 2011-09-07 15:27:40,887 [org.hibernate.cfg.Configuration]
DEBUG: Setting dialect [org.hibernate.dialect.MySQLInnoDBDialect] - 2011-09-07 15:27:40,889 [org.hibernate.id.factory.DefaultIdentifierGeneratorFactory]
INFO: Running hbm2ddl schema export - 2011-09-07 15:27:40,892 [org.hibernate.tool.hbm2ddl.SchemaExport]
DEBUG: import file not found: /import.sql - 2011-09-07 15:27:40,893 [org.hibernate.tool.hbm2ddl.SchemaExport]
INFO: exporting generated schema to database - 2011-09-07 15:27:40,893 [org.hibernate.tool.hbm2ddl.SchemaExport]
INFO: schema export complete - 2011-09-07 15:27:40,893 [org.hibernate.tool.hbm2ddl.SchemaExport]
DEBUG: releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)] - 2011-09-07 15:27:40,893 [org.hibernate.jdbc.ConnectionManager]
DEBUG: transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources! - 2011-09-07 15:27:40,894 [org.hibernate.jdbc.ConnectionManager]
OK, here is what I added to make it work:
Table origTable = persistentClass.getTable();
String schema = origTable.getSchema();
String catalog = origTable.getCatalog();
String name = origTable.getName();
mappings.addTable(schema, catalog, name, origTable.getSubselect(),
origTable.isAbstract());
Table table = mappings.getTable(schema, catalog, name);
Iterator<Column> columnIter = origTable.getColumnIterator();
while (columnIter.hasNext()) {
Column column = columnIter.next();
table.addColumn(column);
}

Hibernate unable to instantiate default tuplizer - cannot find getter

I'm trying to use Hibernate to persist a class that looks like this:
public class Item implements Serializable, Comparable<Item> {
// Item id
private Integer id;
// Description of item in inventory
private String description;
// Number of items described by this inventory item
private int count;
//Category item belongs to
private String category;
// Date item was purchased
private GregorianCalendar purchaseDate;
public Item() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public GregorianCalendar getPurchaseDate() {
return purchaseDate;
}
public void setPurchasedate(GregorianCalendar purchaseDate) {
this.purchaseDate = purchaseDate;
}
My Hibernate mapping file contains the following:
<property name="puchaseDate" type="java.util.GregorianCalendar">
<column name="purchase_date"></column>
</property>
When I try to run, I get error messages indicating there is no getter function for the purchaseDate attribute:
577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!)
577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 20
577 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false
592 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/home_inventory
592 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=root, password=****}
1078 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.1.45
1078 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.12 ( Revision: ${bzr.revision-id} )
1103 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
1107 [main] INFO org.hibernate.engine.jdbc.JdbcSupportLoader - Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
1109 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions)
1110 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
1110 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
1110 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
1110 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15
1110 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
1111 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled
1111 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
1111 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto
1111 [main] INFO org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2
1111 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1
1111 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled
1111 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled
1111 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled
1112 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
1113 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
1113 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {}
1113 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled
1113 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled
1113 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled
1113 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
1113 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
1114 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled
1117 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout
1118 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled
1118 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
1118 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo
1118 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled
1118 [main] INFO org.hibernate.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
1151 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory
org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:110)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:135)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:323)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:475)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:133)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:295)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385)
at service.HibernateSessionFactory.currentSession(HibernateSessionFactory.java:53)
at service.ItemSvcHibImpl.generateReport(ItemSvcHibImpl.java:78)
at service.test.ItemSvcTest.testGenerateReport(ItemSvcTest.java:226)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:164)
at junit.framework.TestCase.runBare(TestCase.java:130)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:107)
... 29 more
Caused by: org.hibernate.PropertyNotFoundException: Could not find a getter for puchaseDate in class domain.Item
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:328)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:321)
at org.hibernate.mapping.Property.getGetter(Property.java:304)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:299)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:158)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
... 34 more
I'm new to Hibernate, so I don't know all the ins and outs, but I do have the getter and setter for the purchaseDate attribute. I don't know what I'm missing here - does anyone else?
It came to me once without any typos. I've added javassist.jar to classpath and it solved the problem.
Further on down the stack trace, it says this:
missing a getter for puchaseDate
You might want to check for typos ;) You're missing an R and setPurchasedate should be setPurchaseDate
It looks like the problem is probably in the capitalization: setPurchasedate() should be setPurchaseDate() (with a capital "D").
If it can help someone:
In my case there were errors in my mapping files. Classes were not referenced by their full package names. I did this mistake because I generated the mappings when my bean classes belonged to the default package (hence no package name; e.g.: Order instead of com.mypackage.Order) and then I moved my bean classes to package (in the example com.mypackage). Unfortunately mapping files did not changed accordingly with the new package definition.
My hint is redo Hibernate reverse engineering and see what it produces, comparing it with your current mapping files.
Pay attention to method name,It is case sensitive!
In my case,it could not recognize getter very well; my property name was uId and I used getUId name for getter name and when I changed it to getuId problem solved!
I included java assit.jar and it worked
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
I experienced the
Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
because I had a momentary lapse of donkeyness when renaming a field on a POJO that I had previously mapped.
I changed the Java attribute name with my trusty IDE refactor hotkey, which does not also change the getter & setter method names. I changed the getter (because it caught my attention with its #Column annotation that I also needed to address because the table column name was changing).
I neglected, however, to change the setter, and that was the cause of the error.

Categories

Resources