Hibernate creating table but not creating entry? - java

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();
}

Related

How to fix: Jooq code does not generate java code for sqlite in memory db from sql script

I am trying to generate Jooq code to use with in memory SQLite.
The problem is, that each new Connection creates a fresh SQLite instance which makes the code creation rely on sql scripts. But when I try to fit my code generation to the documentation the code wont be generated. I believe it still tries to access the database which is empty.
I am also not sure if jooq will work with a non persistent database. The database is intented to only exist during the program run. When the program shuts down the database should be gone. If jooq fetches new connections all troughout the runtime, I have to switch anyway.
Jooq generation:
public static void runJooqCodeGen() throws Exception {
String url = "jdbc:sqlite:";
String driver = "org.sqlite.JDBC";
Configuration configuration = new Configuration().withJdbc(new Jdbc().withDriver(driver).withUrl(url))
.withGenerator(new Generator()
.withDatabase(new Database()
.withProperties(new Property()
.withKey("scripts")
.withValue("src/main/resources/db/Schema.sql")))
.withGenerate(new Generate()
.withPojos(Boolean.TRUE)
.withDeprecationOnUnknownTypes(Boolean.FALSE))
.withTarget(new Target()
.withPackageName("me.leslie.generals.server.persistence.jooq")
.withDirectory("Generals-Server/src/main/java")));
GenerationTool.generate(configuration);
}
src/main/resources/db/Schema.sql:
CREATE TABLE IF NOT EXISTS TROOP(
id INTEGER PRIMARY KEY AUTOINCREMENT,
current_health INTEGER NOT NULL,
max_health INTEGER NOT NULL,
pos_x DOUBLE NOT NULL,
pos_y DOUBLE NOT NULL,
normal_speed DOUBLE NOT NULL,
street_speed DOUBLE NOT NULL,
difficult_terrain_speed DOUBLE NOT NULL,
close_combat_range DOUBLE NOT NULL,
ranged_combat_range DOUBLE NOT NULL,
normal_view_distance DOUBLE NOT NULL,
disadvantaged_view_distance DOUBLE NOT NULL,
advantaged_view_distance DOUBLE NOT NULL
);
CREATE TABLE IF NOT EXISTS ARMY(
id INTEGER,
hq INTEGER,
troop INTEGER,
FOREIGN KEY(hq) REFERENCES TROOP(id),
FOREIGN KEY(troop) REFERENCES TROOP(id),
UNIQUE(hq, troop),
PRIMARY KEY (id, hq, troop)
);
The generation does not finish with an error, but this is the console output.
19:02:57.342 [main] DEBUG org.jooq.codegen.GenerationTool - Input configuration : <onError>FAIL</onError><jdbc><driver>org.sqlite.JDBC</driver><url>jdbc:sqlite:</url></jdbc><generator><name>org.jooq.codegen.DefaultGenerator</name><database><regexMatchesPartialQualification>true</regexMatchesPartialQualification><sqlMatchesPartialQualification>true</sqlMatchesPartialQualification><includes>.*</includes><excludes></excludes><includeExcludeColumns>false</includeExcludeColumns><includeTables>true</includeTables><includeEmbeddables>true</includeEmbeddables><includeRoutines>true</includeRoutines><includeTriggerRoutines>false</includeTriggerRoutines><includePackages>true</includePackages><includePackageRoutines>true</includePackageRoutines><includePackageUDTs>true</includePackageUDTs><includePackageConstants>true</includePackageConstants><includeUDTs>true</includeUDTs><includeSequences>true</includeSequences><includeIndexes>true</includeIndexes><includePrimaryKeys>true</includePrimaryKeys><includeUniqueKeys>true</includeUniqueKeys><includeForeignKeys>true</includeForeignKeys><includeCheckConstraints>true</includeCheckConstraints><includeInvisibleColumns>true</includeInvisibleColumns><recordVersionFields></recordVersionFields><recordTimestampFields></recordTimestampFields><syntheticIdentities></syntheticIdentities><syntheticPrimaryKeys></syntheticPrimaryKeys><overridePrimaryKeys></overridePrimaryKeys><dateAsTimestamp>false</dateAsTimestamp><ignoreProcedureReturnValues>false</ignoreProcedureReturnValues><unsignedTypes>true</unsignedTypes><integerDisplayWidths>true</integerDisplayWidths><inputCatalog></inputCatalog><outputCatalogToDefault>false</outputCatalogToDefault><inputSchema></inputSchema><outputSchemaToDefault>false</outputSchemaToDefault><schemaVersionProvider></schemaVersionProvider><catalogVersionProvider></catalogVersionProvider><orderProvider></orderProvider><forceIntegerTypesOnZeroScaleDecimals>true</forceIntegerTypesOnZeroScaleDecimals><logSlowQueriesAfterSeconds>5</logSlowQueriesAfterSeconds><logSlowResultsAfterSeconds>5</logSlowResultsAfterSeconds><properties><property><key>scripts</key><value>src/main/resources/db/Schema.sql</value></property></properties></database><generate><indexes>true</indexes><relations>true</relations><implicitJoinPathsToOne>true</implicitJoinPathsToOne><deprecated>true</deprecated><deprecationOnUnknownTypes>false</deprecationOnUnknownTypes><instanceFields>true</instanceFields><generatedAnnotation>true</generatedAnnotation><generatedAnnotationType>DETECT_FROM_JDK</generatedAnnotationType><routines>true</routines><sequences>true</sequences><udts>true</udts><queues>true</queues><links>true</links><keys>true</keys><tables>true</tables><embeddables>true</embeddables><records>true</records><recordsImplementingRecordN>true</recordsImplementingRecordN><pojos>true</pojos><pojosEqualsAndHashCode>false</pojosEqualsAndHashCode><pojosToString>true</pojosToString><immutablePojos>false</immutablePojos><serializablePojos>true</serializablePojos><interfaces>false</interfaces><immutableInterfaces>false</immutableInterfaces><serializableInterfaces>true</serializableInterfaces><daos>false</daos><jpaAnnotations>false</jpaAnnotations><validationAnnotations>false</validationAnnotations><springAnnotations>false</springAnnotations><globalObjectReferences>true</globalObjectReferences><globalCatalogReferences>true</globalCatalogReferences><globalSchemaReferences>true</globalSchemaReferences><globalTableReferences>true</globalTableReferences><globalSequenceReferences>true</globalSequenceReferences><globalUDTReferences>true</globalUDTReferences><globalRoutineReferences>true</globalRoutineReferences><globalQueueReferences>true</globalQueueReferences><globalLinkReferences>true</globalLinkReferences><globalKeyReferences>true</globalKeyReferences><javadoc>true</javadoc><comments>true</comments><commentsOnCatalogs>true</commentsOnCatalogs><commentsOnSchemas>true</commentsOnSchemas><commentsOnTables>true</commentsOnTables><commentsOnColumns>true</commentsOnColumns><commentsOnUDTs>true</commentsOnUDTs><commentsOnAttributes>true</commentsOnAttributes><commentsOnPackages>true</commentsOnPackages><commentsOnRoutines>true</commentsOnRoutines><commentsOnParameters>true</commentsOnParameters><commentsOnSequences>true</commentsOnSequences><commentsOnLinks>true</commentsOnLinks><commentsOnQueues>true</commentsOnQueues><commentsOnKeys>true</commentsOnKeys><fluentSetters>false</fluentSetters><javaBeansGettersAndSetters>false</javaBeansGettersAndSetters><varargSetters>true</varargSetters><fullyQualifiedTypes></fullyQualifiedTypes><emptyCatalogs>false</emptyCatalogs><emptySchemas>false</emptySchemas><javaTimeTypes>false</javaTimeTypes><primaryKeyTypes>false</primaryKeyTypes><newline>\n</newline></generate><target><packageName>me.leslie.generals.server.persistence.jooq</packageName><directory>Generals-Server/src/main/java</directory><encoding>UTF-8</encoding><clean>true</clean></target></generator>
19:02:57.424 [main] INFO org.jooq.codegen.GenerationTool - Database : Inferring database org.jooq.meta.sqlite.SQLiteDatabase from URL jdbc:sqlite:
19:02:57.426 [main] INFO org.jooq.codegen.GenerationTool - No <inputCatalog/> was provided. Generating ALL available catalogs instead.
19:02:57.426 [main] INFO org.jooq.codegen.GenerationTool - No <inputSchema/> was provided. Generating ALL available schemata instead.
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - License parameters
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - Thank you for using jOOQ and jOOQ's code generator
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator -
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - Database parameters
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - dialect : SQLITE
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - URL : jdbc:sqlite:
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - target dir : Generals-Server/src/main/java
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - target package : me.leslie.generals.server.persistence.jooq
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - includes : [.*]
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - excludes : []
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - includeExcludeColumns : false
19:02:57.524 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator -
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - JavaGenerator parameters
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - ----------------------------------------------------------
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - annotations (generated): true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - annotations (JPA: any) : false
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - annotations (JPA: version):
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - annotations (validation): false
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on attributes : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on catalogs : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on columns : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on keys : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on links : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on packages : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on parameters : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on queues : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on routines : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on schemas : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on sequences : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on tables : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - comments on udts : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - daos : false
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - deprecated code : true
19:02:57.524 [main] INFO org.jooq.codegen.JavaGenerator - global references (any): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (catalogs): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (keys): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (links): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (queues): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (routines): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (schemas): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (sequences): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (tables): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - global references (udts): true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - indexes : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - instance fields : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - interfaces : false
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - interfaces (immutable) : false
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - javadoc : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - keys : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - links : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - pojos : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - pojos (immutable) : false
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - queues : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - records : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - routines : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - sequences : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - table-valued functions : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - tables : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - udts : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - relations : true
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - ----------------------------------------------------------
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -
19:02:57.525 [main] INFO org.jooq.codegen.AbstractGenerator - Generation remarks
19:02:57.525 [main] INFO org.jooq.codegen.AbstractGenerator - ----------------------------------------------------------
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator -
19:02:57.525 [main] INFO org.jooq.codegen.JavaGenerator - ----------------------------------------------------------
19:02:57.526 [main] INFO org.jooq.codegen.JavaGenerator - Generating catalogs : Total: 1
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - ARRAYs fetched : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Enums fetched : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Packages fetched : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Routines fetched : 0 (0 included, 0 excluded)
19:02:57.526 [main] INFO org.jooq.meta.AbstractDatabase - Sequences fetched : 0 (0 included, 0 excluded)
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.jooq.tools.reflect.Reflect (file:/home/leslie/.m2/repository/org/jooq/jooq/3.12.1/jooq-3.12.1.jar) to constructor java.lang.invoke.MethodHandles$Lookup(java.lang.Class)
WARNING: Please consider reporting this to the maintainers of org.jooq.tools.reflect.Reflect
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
19:02:57.725 [main] INFO org.jooq.Constants -
######################################
######################################
################ ## ##########
#################### ##########
################ ## ## ##########
########## #### ## ## ##########
########## ## ##########
######################################
######################################
########## ## ##########
########## ## ## #### ##########
########## ## ## #### ##########
########## ## # # ##########
########## ## ##########
####################### #############
######################################
###################################### Thank you for using jOOQ 3.12.1
19:02:57.732 [main] DEBUG org.jooq.tools.LoggerListener - Executing query : select 1 one
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - Fetched result : +----+
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - : | one|
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - : +----+
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - : | 1|
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - : +----+
19:02:57.788 [main] DEBUG org.jooq.tools.LoggerListener - Fetched row(s) : 1
19:02:57.791 [main] DEBUG org.jooq.tools.LoggerListener - Executing query : select sqlite_master.name from sqlite_master where sqlite_master.type in (?, ?) order by sqlite_master.name
19:02:57.792 [main] DEBUG org.jooq.tools.LoggerListener - -> with bind values : select sqlite_master.name from sqlite_master where sqlite_master.type in ('table', 'view') order by sqlite_master.name
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener - Fetched result : +----+
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener - : |name|
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener - : +----+
19:02:57.793 [main] DEBUG org.jooq.tools.LoggerListener - Fetched row(s) : 0
19:02:57.793 [main] INFO org.jooq.meta.AbstractDatabase - Tables fetched : 0 (0 included, 0 excluded)
19:02:57.793 [main] INFO org.jooq.meta.AbstractDatabase - UDTs fetched : 0 (0 included, 0 excluded)
19:02:57.793 [main] INFO org.jooq.codegen.JavaGenerator - Excluding empty catalog :
19:02:57.793 [main] INFO org.jooq.codegen.JavaGenerator - Removing excess files
Process finished with exit code 0
If you want to use the DDLDatabase as documented in the link you've posted, you should:
remove the JDBC connection parameters
add the DDLDatabase as a database implementation, to replace the default SQLiteDatabase (which is derived from your JDBC connection parameters).
In other words, try this:
public static void runJooqCodeGen() throws Exception {
// Removed this
/* String url = "jdbc:sqlite:";
String driver = "org.sqlite.JDBC"; */
Configuration configuration = new Configuration()/*.withJdbc(new Jdbc()
.withDriver(driver).withUrl(url))*/
.withGenerator(new Generator()
.withDatabase(new Database()
// Added this
.withName("org.jooq.meta.extensions.ddl.DDLDatabase")
.withProperties(new Property()
.withKey("scripts")
.withValue("src/main/resources/db/Schema.sql")))
.withGenerate(new Generate()
.withPojos(Boolean.TRUE)
.withDeprecationOnUnknownTypes(Boolean.FALSE))
.withTarget(new Target()
.withPackageName("me.leslie.generals.server.persistence.jooq")
.withDirectory("Generals-Server/src/main/java")));
GenerationTool.generate(configuration);
}

Docx4J is not replacing placeholders

I am trying to replace a simple 'Place Holderin MS Word 2007 usingDocx4J. I created the placeholder byReference > Insert Citation > Add New Placeholder`
Below is my Docx4J code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.ContentAccessor;
import org.docx4j.wml.Text;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Yohan
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new Main();
}
public Main()
{
try
{
WordprocessingMLPackage template = getTemplate("C:/Users/Yohan/Desktop/Yohan.docx");
replacePlaceholder(template,"Plane","Placeholder1");
writeDocxToStream(template,"C:/Users/Yohan/Desktop/Yohan2.docx");
System.out.println("Operation Completed");
}
catch(Exception e)
{
e.printStackTrace();
}
}
private WordprocessingMLPackage getTemplate(String name) throws Docx4JException, FileNotFoundException {
WordprocessingMLPackage template = WordprocessingMLPackage.load(new FileInputStream(new File(name)));
return template;
}
private static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
private void replacePlaceholder(WordprocessingMLPackage template, String name, String placeholder ) {
List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class);
for (Object text : texts) {
Text textElement = (Text) text;
if (textElement.getValue().equals(placeholder)) {
textElement.setValue(name);
}
}
}
private void writeDocxToStream(WordprocessingMLPackage template, String target) throws IOException, Docx4JException {
File f = new File(target);
template.save(f);
}
}
This generated the below in Netbeans console.
[main] INFO org.docx4j.jaxb.Context - java.vendor=Oracle Corporation
[main] INFO org.docx4j.jaxb.Context - java.version=1.8.0_05
[main] INFO org.docx4j.jaxb.Context - No MOXy JAXB config found; assume not intended..
[main] INFO org.docx4j.jaxb.NamespacePrefixMapperUtils - Using NamespacePrefixMapperSunInternal, which is suitable for Java 6
[main] INFO org.docx4j.jaxb.Context - Using Java 6/7 JAXB implementation
[main] INFO org.docx4j.jaxb.Context - Not using MOXy; using com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl
[main] WARN org.docx4j.utils.ResourceUtils - Couldn't get resource: docx4j.properties
[main] WARN org.docx4j.Docx4jProperties - Couldn't find/read docx4j.properties; docx4j.properties not found via classloader.
[main] INFO org.docx4j.XmlUtils - Using com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
[main] INFO org.docx4j.XmlUtils - Using com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
[main] INFO org.docx4j.openpackaging.contenttype.ContentTypeManager - Detected WordProcessingML package
[main] INFO org.docx4j.openpackaging.io3.Load3 - Instantiated package of type org.docx4j.openpackaging.packages.WordprocessingMLPackage
[main] INFO org.docx4j.utils.XPathFactoryUtil - xpath implementation: org.apache.xpath.jaxp.XPathFactoryImpl
[main] INFO org.docx4j.openpackaging.io.Load - Found a CustomXmlPart, named /customXml/item1.xml
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - Lazily unmarshalling /customXml/itemProps1.xml
[main] INFO org.docx4j.openpackaging.io.Load - Identified/registered ds:itemId {2da45ade-e2fe-4251-9c73-a623aa57ebb0}
[main] INFO org.docx4j.openpackaging.io3.Load3 - package read; elapsed time: 10932 ms
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - Lazily unmarshalling /word/document.xml
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPartXPathAware - For org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart, unmarshall via binder
[main] INFO org.docx4j.openpackaging.contenttype.ContentTypeManager - marshalling org.docx4j.openpackaging.contenttype.ContentTypeManager ...
[main] INFO org.docx4j.jaxb.NamespacePrefixMapperUtils - Using NamespacePrefixMapperSunInternal, which is suitable for Java 6
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.relationships.RelationshipsPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.relationships.RelationshipsPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.WordprocessingML.BibliographyPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.relationships.RelationshipsPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.CustomXmlDataStoragePropertiesPart
[main] INFO org.docx4j.openpackaging.io3.Save - ...Done!
Operation Completed
However in Yohan2.docx, nothing is changed, it is a pure copy of Yohan.docx. What have I done wrong here?
UPDATE
I tested the MERGEFIELD example from the GITHUB but it also didn't work. Below is the output printed in console
[main] INFO org.docx4j.jaxb.Context - java.vendor=Oracle Corporation
[main] INFO org.docx4j.jaxb.Context - java.version=1.8.0_05
[main] INFO org.docx4j.jaxb.Context - No MOXy JAXB config found; assume not intended..
[main] INFO org.docx4j.jaxb.NamespacePrefixMapperUtils - Using NamespacePrefixMapperSunInternal, which is suitable for Java 6
[main] INFO org.docx4j.jaxb.Context - Using Java 6/7 JAXB implementation
[main] INFO org.docx4j.jaxb.Context - Not using MOXy; using com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl
[main] WARN org.docx4j.utils.ResourceUtils - Couldn't get resource: docx4j.properties
[main] WARN org.docx4j.Docx4jProperties - Couldn't find/read docx4j.properties; docx4j.properties not found via classloader.
[main] INFO org.docx4j.XmlUtils - Using com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl
[main] INFO org.docx4j.XmlUtils - Using com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
[main] INFO org.docx4j.openpackaging.contenttype.ContentTypeManager - Detected WordProcessingML package
[main] INFO org.docx4j.openpackaging.io3.Load3 - Instantiated package of type org.docx4j.openpackaging.packages.WordprocessingMLPackage
[main] INFO org.docx4j.utils.XPathFactoryUtil - xpath implementation: org.apache.xpath.jaxp.XPathFactoryImpl
[main] WARN org.docx4j.openpackaging.contenttype.ContentTypeManager - DefaultPart used for part '/word/stylesWithEffects.xml' of content type 'application/vnd.ms-word.stylesWithEffects+xml'
[main] INFO org.docx4j.openpackaging.io3.Load3 - package read; elapsed time: 14766 ms
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - Lazily unmarshalling /word/document.xml
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPartXPathAware - For org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart, unmarshall via binder
[main] INFO org.docx4j.model.fields.merge.MailMerger - Found 9 fields
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'Kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'KunDenName'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'KUNDENNAME'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'Kundenstrasse'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'yourdate'
[main] INFO org.docx4j.model.fields.DateFormatInferencer - Infering dates based using International formats
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'yournumber'
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - Lazily unmarshalling /word/settings.xml
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPartXPathAware - For org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart, unmarshall via binder
[main] INFO org.docx4j.openpackaging.contenttype.ContentTypeManager - marshalling org.docx4j.openpackaging.contenttype.ContentTypeManager ...
[main] INFO org.docx4j.jaxb.NamespacePrefixMapperUtils - Using NamespacePrefixMapperSunInternal, which is suitable for Java 6
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.relationships.RelationshipsPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.relationships.RelationshipsPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart
[main] WARN org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart -
[main] INFO org.docx4j.openpackaging.io3.Save - ...Done!
[main] INFO org.docx4j.model.fields.merge.MailMerger - Found 9 fields
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'Kundenname'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'KunDenName'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'KUNDENNAME'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'Kundenstrasse'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'yourdate'
[main] INFO org.docx4j.model.fields.merge.MailMerger - Key: 'yournumber'
[main] INFO org.docx4j.openpackaging.contenttype.ContentTypeManager - marshalling org.docx4j.openpackaging.contenttype.ContentTypeManager ...
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.relationships.RelationshipsPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.relationships.RelationshipsPart
[main] INFO org.docx4j.openpackaging.parts.JaxbXmlPart - marshalling org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart
[main] WARN org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart -
[main] INFO org.docx4j.openpackaging.io3.Save - ...Done!
A placeholder inserted via Reference > Insert Citation > Add New Placeholder results in something like:
<w:sdt>
<w:sdtPr>
<w:id w:val="-963732549"/>
<w:citation/>
</w:sdtPr>
<w:sdtContent>
<w:r>
<w:fldChar w:fldCharType="begin"/>
</w:r>
<w:r>
<w:rPr>
<w:lang w:val="en-AU"/>
</w:rPr>
<w:instrText xml:space="preserve"> CITATION PL1 \l 3081 </w:instrText>
</w:r>
<w:r>
<w:fldChar w:fldCharType="separate"/>
</w:r>
<w:r>
<w:rPr>
<w:noProof/>
<w:lang w:val="en-AU"/>
</w:rPr>
<w:t>(PL1)</w:t>
</w:r>
<w:r>
<w:fldChar w:fldCharType="end"/>
</w:r>
</w:sdtContent>
</w:sdt>
ie a CITATION field wrapped in a content control.
docx4j has an API for replacing MERGEFIELD and DOCPROPERTY fields, but not CITATION fields.
Is there a particular reason you are trying to use a CITATION field?
If you can swap to MERGEFIELD or DOCPROPERTY field, I'd do that. Otherwise, you could examine docx4j's code for handling those, and adapt it to handling CITATION.
Place Holder in Insert > Quick Parts > Field
Select MergeField
Copy merge field name as appears in the document together with the arrow characters to your code.
replacePlaceholder(template,"Plane","placeholdernamewitharrowcharacters");

Could not prepare statement while saving via entity manager

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!

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