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
Related
I have an entity class Product that i was given READ grant on the whole entity and UPDATE grant ONLY on the price field in the database. So whenever i call productDao.update(product), even if I changed only the price field value, i`m getting
<2020-09-17 14:33:26.735 WARN 26939 --- [ (self-tuning)'] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1031, SQLState: 42000>
<2020-09-17 14:33:26.735 ERROR 26939 --- [ (self-tuning)'] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-01031: insufficient privileges>
<2020-09-17 14:33:26.736 INFO 26939 --- [ (self-tuning)'] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements>
<2020-09-17 14:33:26.737 ERROR 26939 --- [ (self-tuning)'] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.SQLGrammarException: could not execute statement]>
Try using dynamic update, the generated SQL will only try to update the columns that have been modified
Maybe instead of calling the default .update() method implement your own updating method in which you just execute a HQL update statement which updates one field based on your object's value?
Maybe you could try to annotate other properties of Entity as #Column(updatable = false)
I have been recreating an old app from 2.2.2 to 3.1.2
The following below is the error I am getting because of a database problem.
So far I have not found a solution online about this major error. Grails will not run while the errors exist.
I am fairly new to grails and as such am unsure about the errors listed below. any help will be greatly appreciated.
Using:
Grails Version: 3.1.2
MySQL Workbench 6
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: create table location (id bigint not null auto_
increment, version bigint not null, location varchar(255) not null, specific varchar(255) not null, primary key (id)) EN
GINE=InnoDB
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'specific varchar(255) not null, primary key (id)) ENGINE=
InnoDB' at line 1
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: create table update (id bigint not null auto_in
crement, version bigint not null, asset_id bigint not null, location_id bigint not null, note varchar(1000), occurred_at
datetime not null, occurred_by_id bigint not null, state_id bigint not null, primary key (id)) ENGINE=InnoDB
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'update (id bigint not null auto_increment, version bigint
not null, asset_id big' at line 1
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table update add constraint FK_6xengovrbl
vcx3o2p48wii9up foreign key (asset_id) references asset (id)
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'update add constraint FK_6xengovrblvcx3o2p48wii9up foreig
n key (asset_id) refere' at line 1
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table update add constraint FK_qlyn7y3hqg
n4gcyidimltadkt foreign key (location_id) references location (id)
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'update add constraint FK_qlyn7y3hqgn4gcyidimltadkt foreig
n key (location_id) ref' at line 1
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table update add constraint FK_7bbvhf1v8f
5ajhqq9oucd8fsq foreign key (occurred_by_id) references user (id)
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'update add constraint FK_7bbvhf1v8f5ajhqq9oucd8fsq foreig
n key (occurred_by_id) ' at line 1
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful: alter table update add constraint FK_p07l6jl32s
obfymx3otspk2t3 foreign key (state_id) references state (id)
ERROR org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'update add constraint FK_p07l6jl32sobfymx3otspk2t3 foreig
n key (state_id) refere' at line 1
ERROR org.springframework.boot.SpringApplication - Application startup failed
grails.validation.ValidationException: Validation Error(s) occurred during save():
- Field error in object 'State' on field 'updates': rejected value [{}]; codes [State.updates.typeMismatch.error,State.u
pdates.typeMismatch,state.updates.typeMismatch.error,state.updates.typeMismatch,typeMismatch.State.updates,typeMismatch.
updates,typeMismatch.java.util.Set,typeMismatch]; arguments [updates]; default message [Could not find matching construc
tor for: java.util.Set()]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_65]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_65]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8
.0_65]
at java.lang.reflect.Constructor.newInstance(Constructor.java:422) ~[na:1.8.0_65]
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1075) ~
[springloaded-1.2.5.RELEASE.jar:1.2.5.RELEASE]
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83) ~[groovy-2.4.6.jar:2.4.6]
at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:77) ~[groovy-2.4.
6.jar:2.4.6]
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1714) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1531) ~[groovy-2.4.6.jar:2.4.6]
at org.codehaus.groovy.runtime.InvokerHelper.invokeConstructorOf(InvokerHelper.java:954) ~[groovy-2.4.6.jar:2.4.
6]
at org.codehaus.groovy.runtime.DefaultGroovyMethods.newInstance(DefaultGroovyMethods.java:15640) ~[groovy-2.4.6.
jar:2.4.6]
at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi.save(AbstractHibernateGormInstanceApi.groovy:131) ~
[grails-datastore-gorm-hibernate-core-5.0.2.RELEASE.jar:na]
at org.grails.datastore.gorm.GormEntity$Trait$Helper.save(GormEntity.groovy:140) ~[grails-datastore-gorm-5.0.2.R
ELEASE.jar:na]
at org.grails.datastore.gorm.GormEntity$Trait$Helper$save.call(Unknown Source) ~[na:na]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-2.4.6.jar:2.4.6
]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-2.4.6.jar:2.4.6
]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) [groovy-2.4.6.jar:2.4.6
]
at State.save(State.groovy) ~[main/:na]
at State.save(State.groovy) ~[main/:na]
at org.grails.datastore.gorm.GormEntity$save.call(Unknown Source) ~[na:na]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-2.4.6.jar:2.4.6
]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-2.4.6.jar:2.4.6
]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) [groovy-2.4.6.jar:2.4.6
]
at BootStrap$_closure1.doCall(BootStrap.groovy:10) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1426) ~[springloa
ded-1.2.5.RELEASE.jar:1.2.5.RELEASE]
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) ~[groovy-2.4.6.jar:2.4.6]
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) ~[groovy-2.4.6
.jar:2.4.6]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1021) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1086) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1021) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.Closure.call(Closure.java:426) ~[groovy-2.4.6.jar:2.4.6]
at groovy.lang.Closure.call(Closure.java:420) ~[groovy-2.4.6.jar:2.4.6]
at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:437) ~[grails-bootstrap-3.1.2.jar:3
.1.2]
at grails.util.Environment.executeForEnvironment(Environment.java:430) ~[grails-bootstrap-3.1.2.jar:3.1.2]
at grails.util.Environment.executeForCurrentEnvironment(Environment.java:406) ~[grails-bootstrap-3.1.2.jar:3.1.2
]
at org.grails.web.servlet.boostrap.DefaultGrailsBootstrapClass.callInit(DefaultGrailsBootstrapClass.java:62) ~[g
rails-web-3.1.2.jar:3.1.2]
at org.grails.web.servlet.context.GrailsConfigUtils.executeGrailsBootstraps(GrailsConfigUtils.java:65) ~[grails-
web-3.1.2.jar:3.1.2]
at org.grails.plugins.web.servlet.context.BootStrapClassRunner.onStartup(BootStrapClassRunner.groovy:53) ~[grail
s-plugin-controllers-3.1.2.jar:3.1.2]
at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy:24
0) ~[grails-core-3.1.2.jar:3.1.2]
at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy) ~
[grails-core-3.1.2.jar:3.1.2]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMult
icaster.java:163) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMult
icaster.java:136) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:3
81) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:3
35) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:
855) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationC
ontext.java:140) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~
[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext
.java:118) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) ~[spring-boot-1.3.2.RELEASE.ja
r:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) ~[spring-boot-
1.3.2.RELEASE.jar:1.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-1.3.2.RELEASE.jar:1.
3.2.RELEASE]
at grails.boot.GrailsApp.run(GrailsApp.groovy:55) [grails-core-3.1.2.jar:3.1.2]
at grails.boot.GrailsApp.run(GrailsApp.groovy:365) [grails-core-3.1.2.jar:3.1.2]
at grails.boot.GrailsApp.run(GrailsApp.groovy:354) [grails-core-3.1.2.jar:3.1.2]
at grails.boot.GrailsApp$run.call(Unknown Source) [grails-core-3.1.2.jar:3.1.2]
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) [groovy-2.4.6.jar:2.4.6
]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) [groovy-2.4.6.jar:2.4.6
]
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) [groovy-2.4.6.jar:2.4.6
]
at Application.main(Application.groovy:6) [main/:na]
My application.yml that I am recoding is this:
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
dataSource:
dataSource:
pooled: true
url: jdbc:mysql://localhost:3306/db
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
username: root
password: root
environments:
development:
dataSource:
dbCreate: update
url: jdbc:mysql://localhost:3306/db
test:
dataSource:
dbCreate: update
url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
production:
dataSource:
dbCreate: update
url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
the DataSource.groovy of old app that I am basing on is this:
dataSource {
pooled = true
driverClassName = "org.h2.Driver"
username = "sa"
password = ""
}
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
}
// environment specific settings
environments {
development {
dataSource {
dbCreate = "update"
url = "jdbc:mysql://localhost:3306/harbor"
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = "root"
properties {
maxActive = 100
maxIdle = 25
minIdle = 5
initialSize = 10
minEvictableIdleTimeMillis = 60000
timeBetweenEvictionRunsMillis = 60000
maxWait = 10000
}
}
/*dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}*/
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}
}
production {
dataSource {
dbCreate = "update"
url = "jdbc:mysql://localhost:3306/db"
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = "root"
properties {
maxActive = 100
maxIdle = 25
minIdle = 5
initialSize = 10
minEvictableIdleTimeMillis = 60000
timeBetweenEvictionRunsMillis = 60000
maxWait = 10000
}
}
/*
dataSource {
dbCreate = "update"
url = "jdbc:h2:prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
pooled = true
properties {
maxActive = -1
minEvictableIdleTimeMillis=1800000
timeBetweenEvictionRunsMillis=1800000
numTestsPerEvictionRun=3
testOnBorrow=true
testWhileIdle=true
testOnReturn=true
validationQuery="SELECT 1"
}
}*/
}
}
From the first line of your errors, it looks like one of your data classes has an attribute named 'specific'.
Unfortunately, that is a MySQL reserved word so you can't use it. You'll need to change the name of the field.
Similarly, your second error is for a table called 'update', which is also a reserved word.
For a list of reserved words see, for example, https://dev.mysql.com/doc/refman/5.7/en/keywords.html. You may be on an older version of MySQL, but as they point out it's always good to check reserved words on later versions so you don't make it difficult to upgrade to that version of MySQL later.
As an alternative to renaming things, you should be able to tell Grails to escape the names. See for example, http://blog.adamcreeger.com/2010/05/random-grails-tip-using-db-reserved.html
application.yml of mine now
---
grails:
profile: web
codegen:
defaultPackage: grailsapp
info:
app:
name: '#info.app.name#'
version: '#info.app.version#'
grailsVersion: '#info.app.grailsVersion#'
spring:
groovy:
template:
check-template-location: false
---
grails:
mime:
disable:
accept:
header:
userAgents:
- Gecko
- WebKit
- Presto
- Trident
types:
all: '*/*'
atom: application/atom+xml
css: text/css
csv: text/csv
form: application/x-www-form-urlencoded
html:
- text/html
- application/xhtml+xml
js: text/javascript
json:
- application/json
- text/json
multipartForm: multipart/form-data
pdf: application/pdf
rss: application/rss+xml
text: text/plain
hal:
- application/hal+json
- application/hal+xml
xml:
- text/xml
- application/xml
urlmapping:
cache:
maxsize: 1000
controllers:
defaultScope: singleton
converters:
encoding: UTF-8
views:
default:
codec: html
gsp:
encoding: UTF-8
htmlcodec: xml
codecs:
expression: html
scriptlets: html
taglib: none
staticparts: none
---
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
endpoints:
jmx:
unique-names: true
dataSource:
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
username: root
password: root
environments:
development:
dataSource:
dbCreate: update
url: jdbc:mysql://localhost/inventory
test:
dataSource:
driverClassName: org.h2.Driver
username: sa
password:
dbCreate: update
url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
production:
dataSource:
dbCreate: update
url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
I am working on Spring MVC,
On project startup i have set database to import default sql
with hibernate configuration hibernate.hbm2ddl.import_files.
Data inside import.sql is encoded with UTF-8.
Console Output
ERROR: org.hibernate.tool.hbm2ddl.SchemaExport - HHH000388:
Unsuccessful: INSERT INTO menu (id, DATE_CREATED, DATE_DELETED,
DATE_UPDATED, TITLE_ENG, TITLE_GEO, TITLE_RUS, ENABLED, PARENT_ID,
URL, SITE_ID, USER_ID) VALUES
ERROR:
org.hibernate.tool.hbm2ddl.SchemaExport - You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '' at line 1
ERROR:
org.hibernate.tool.hbm2ddl.SchemaExport - HHH000388: Unsuccessful: (1,
'2015-09-10 12:00:00', NULL, NULL, 'About Us', N'ჩვენს
შეს�ხებ', 'About Us', b'1', NULL, '/article/view/1', 3,
1).
Make sure you are setting the JDBC driver to use UTF-8:
jdbc:mysql://dbname?useUnicode=true&characterEncoding=utf-8
In persistence.xml, set the hibernate connection charset:
<property name="hibernate.connection.charSet" value="UTF-8"/>
If your resources/import.sql file is multi-line, add:
<property
name="hibernate.hbm2ddl.import_files_sql_extractor"
value="org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor"
/>
or for Spring Boot, in application.properties:
spring.jpa.properties.hibernate.connection.charSet=UTF-8
spring.jpa.properties.hibernate.hbm2ddl.import_files_sql_extractor=org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor
I just started using flywaydb and just for a test tried with create and insert queries and fired the migrate but it ignored all my create table scripts :(
I used -X option for debug and found a strange line
DEBUG: DDL Transactions Supported: false
Seems if i made it true, it will work.
Does anyone faced this issue, if yes how to get rid of this?
i have did this on new schema, with clean-init-migrate
Full stacktrace below:
[ec2-user#ec2 flyway]$ ./flyway -X clean
/usr/bin/tput
Flyway (Command-line Tool) v.3.0
DEBUG: Adding location to classpath: /home/ec2-user/installables/flyway-3.0/bin/../jars/mysql-connector-java-5.1.26.jar
Database: jdbc:mysql://0.0.0.0:3306/test (MySQL 5.5)
DEBUG: DDL Transactions Supported: false
DEBUG: Schema: test
DEBUG: Cleaning schema `test` ...
Cleaned schema `test` (execution time 00:00.025s)
[ec2-user#ec2 flyway]$
[ec2-user#ec2 flyway]$ ./flyway -X init
/usr/bin/tput
Flyway (Command-line Tool) v.3.0
DEBUG: Adding location to classpath: /home/ec2-user/installables/flyway-3.0/bin/../jars/mysql-connector-java-5.1.26.jar
Database: jdbc:mysql://0.0.0.0:3306/test (MySQL 5.5)
DEBUG: DDL Transactions Supported: false
DEBUG: Schema: test
DEBUG: Schema `test` already exists. Skipping schema creation.
Creating Metadata table: `test`.`schema_version`
DEBUG: Found statement at line 17: CREATE TABLE `test`.`schema_version` (
`version_rank` INT NOT NULL,
`installed_rank` INT NOT NULL,
`version` VARCHAR(50) NOT NULL,
`description` VARCHAR(200) NOT NULL,
`type` VARCHAR(20) NOT NULL,
`script` VARCHAR(1000) NOT NULL,
`checksum` INT,
`installed_by` VARCHAR(100) NOT NULL,
`installed_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`execution_time` INT NOT NULL,
`success` BOOL NOT NULL
) ENGINE=InnoDB
DEBUG: Found statement at line 30: ALTER TABLE `test`.`schema_version` ADD CONSTRAINT `schema_version_pk` PRIMARY KEY (`version`)
DEBUG: Found statement at line 32: CREATE INDEX `schema_version_vr_idx` ON `test`.`schema_version` (`version_rank`)
DEBUG: Found statement at line 33: CREATE INDEX `schema_version_ir_idx` ON `test`.`schema_version` (`installed_rank`)
DEBUG: Found statement at line 34: CREATE INDEX `schema_version_s_idx` ON `test`.`schema_version` (`success`)
DEBUG: Executing SQL: CREATE TABLE `test`.`schema_version` (
`version_rank` INT NOT NULL,
`installed_rank` INT NOT NULL,
`version` VARCHAR(50) NOT NULL,
`description` VARCHAR(200) NOT NULL,
`type` VARCHAR(20) NOT NULL,
`script` VARCHAR(1000) NOT NULL,
`checksum` INT,
`installed_by` VARCHAR(100) NOT NULL,
`installed_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`execution_time` INT NOT NULL,
`success` BOOL NOT NULL
) ENGINE=InnoDB
DEBUG: Executing SQL: ALTER TABLE `test`.`schema_version` ADD CONSTRAINT `schema_version_pk` PRIMARY KEY (`version`)
DEBUG: Executing SQL: CREATE INDEX `schema_version_vr_idx` ON `test`.`schema_version` (`version_rank`)
DEBUG: Executing SQL: CREATE INDEX `schema_version_ir_idx` ON `test`.`schema_version` (`installed_rank`)
DEBUG: Executing SQL: CREATE INDEX `schema_version_s_idx` ON `test`.`schema_version` (`success`)
DEBUG: Metadata table `test`.`schema_version` created.
DEBUG: MetaData table `test`.`schema_version` successfully updated to reflect changes
Schema initialized with version: 1
[ec2-user#ec2 flyway]$ ./flyway -X migrate
/usr/bin/tput
Flyway (Command-line Tool) v.3.0
DEBUG: Adding location to classpath: /home/ec2-user/installables/flyway-3.0/bin/../jars/mysql-connector-java-5.1.26.jar
Database: jdbc:mysql://0.0.0.0:3306/test (MySQL 5.5)
DEBUG: DDL Transactions Supported: false
DEBUG: Schema: test
DEBUG: Spring Jdbc available: false
DEBUG: Validating migrations ...
DEBUG: Scanning for filesystem resources at '/home/ec2-user/installables/flyway-3.0/bin/../sql' (Prefix: 'V', Suffix: '.sql')
DEBUG: Scanning for resources in path: /home/ec2-user/installables/flyway-3.0/bin/../sql (/home/ec2-user/installables/flyway-3.0/bin/../sql)
DEBUG: Found filesystem resource: /home/ec2-user/installables/flyway-3.0/bin/../sql/V1__cr_tbl.sql
DEBUG: Found filesystem resource: /home/ec2-user/installables/flyway-3.0/bin/../sql/V2__Add_people.sql
Validated 2 migrations (execution time 00:00.032s)
DEBUG: Schema `test` already exists. Skipping schema creation.
DEBUG: Locking table `test`.`schema_version`...
DEBUG: Lock acquired for table `test`.`schema_version`
Current version of schema `test`: 1
Migrating schema `test` to version 2
DEBUG: Found statement at line 1: insert into PERSON (ID, NAME) values (1, 'Axel')
DEBUG: Found statement at line 2: insert into PERSON (ID, NAME) values (2, 'Mr. Foo')
DEBUG: Found statement at line 3: insert into PERSON (ID, NAME) values (3, 'Ms. Bar')
DEBUG: Executing SQL: insert into PERSON (ID, NAME) values (1, 'Axel')
DEBUG: Rolling back transaction...
DEBUG: Transaction rolled back
ERROR: Migration of schema `test` to version 2 failed! Please restore backups and roll back database and code!
DEBUG: MetaData table `test`.`schema_version` successfully updated to reflect changes
ERROR: Unexpected error
org.flywaydb.core.internal.dbsupport.FlywaySqlScriptException: Error executing statement at line 1: insert into PERSON (ID, NAME) values (1, 'Axel')
at org.flywaydb.core.internal.dbsupport.SqlScript.execute(SqlScript.java:91)
at org.flywaydb.core.internal.resolver.sql.SqlMigrationExecutor.execute(SqlMigrationExecutor.java:73)
at org.flywaydb.core.internal.command.DbMigrate$5.doInTransaction(DbMigrate.java:287)
at org.flywaydb.core.internal.command.DbMigrate$5.doInTransaction(DbMigrate.java:285)
at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:72)
at org.flywaydb.core.internal.command.DbMigrate.applyMigration(DbMigrate.java:285)
at org.flywaydb.core.internal.command.DbMigrate.access$800(DbMigrate.java:46)
at org.flywaydb.core.internal.command.DbMigrate$2.doInTransaction(DbMigrate.java:207)
at org.flywaydb.core.internal.command.DbMigrate$2.doInTransaction(DbMigrate.java:156)
at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:72)
at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:156)
at org.flywaydb.core.Flyway$1.execute(Flyway.java:864)
at org.flywaydb.core.Flyway$1.execute(Flyway.java:811)
at org.flywaydb.core.Flyway.execute(Flyway.java:1171)
at org.flywaydb.core.Flyway.migrate(Flyway.java:811)
at org.flywaydb.commandline.Main.executeOperation(Main.java:120)
at org.flywaydb.commandline.Main.main(Main.java:88)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.PERSON' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2812)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2761)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:894)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:732)
at org.flywaydb.core.internal.dbsupport.JdbcTemplate.executeStatement(JdbcTemplate.java:235)
at org.flywaydb.core.internal.dbsupport.SqlScript.execute(SqlScript.java:89)
... 16 more
This simply means your DB does not support DDL transactions. Use a different like PostgreSQL, DB2 or SqlServer if you need that.
Now as to why your scripts are not being picked up, this is impossible to tell from your question.
Start with a getting started tutorial and once successful, adapt it to your project.
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!