I'm using Wicket in combination with Spring and Hibernate, at least that's what I'm trying to do, the problem comes with auto generating the tables with Hibernate annotations.
I've been trying many changes in the configuration but can't seem to figure out why my configuration doesn't generate any tables. And I'm hoping someone can point me in the right direction, even about the Spring configuration I'm not sure.
I've included all the files I'm using to try to make this work in links, so that it won't be a very long list of configuration files.
I'm using the following class with annotations, http://schrealex.com/downloads/User.java:
#Entity
#Table(name="user")
public class User {
#Id
#Column(name="user_id", unique=true, nullable=false)
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="birthDate")
private Date birthDate;
#Column(name="email")
private String email;
#Column(name="profile_image")
private String profile_image;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
// Getter and Setter methods
}
I'm using the following dependencies described in my pom.xml:
http://schrealex.com/downloads/pom.xml
I'm using the following configuration in applicationContext.xml and properties:
http://schrealex.com/downloads/application.properties
http://schrealex.com/downloads/applicationContext.xml
And finally web.xml:
http://schrealex.com/downloads/web.xml
If I'm missing any files you'd like to see, just ask.
Edit :-
Added start up logging:
SSL access to the quickstart has been enabled on port 8443
You can access the application using SSL on https://localhost:8443
>>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP
INFO - Server - jetty-7.6.3.v20120416
INFO - tandardDescriptorProcessor - NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
INFO - / - Initializing Spring root WebApplicationContext
INFO - ContextLoader - Root WebApplicationContext: initialization started
INFO - XmlWebApplicationContext - Refreshing org.springframework.web.context.support.XmlWebApplicationContext#1c35ce99: display name [Root WebApplicationContext]; startup date [Wed Nov 28 19:53:33 CET 2012]; root of context hierarchy
INFO - XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
INFO - XmlWebApplicationContext - Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext#1c35ce99]: org.springframework.beans.factory.support.DefaultListableBeanFactory#2a9b5441
INFO - pertyPlaceholderConfigurer - Loading properties file from URL [file:/C:/Users/CE_REAL/Documents/Development/media-database/target/classes/application.properties]
INFO - DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#2a9b5441: defining beans [wicketApplication,placeholderConfigurer,dataSource,transactionManager,transactionInterceptor,managerTemplate,sessionFactory]; root of factory hierarchy
INFO - Version - Hibernate Annotations 3.4.0.GA
INFO - Environment - Hibernate 3.2.6
INFO - Environment - hibernate.properties not found
INFO - Environment - Bytecode provider name : cglib
INFO - Environment - using JDK 1.4 java.sql.Timestamp handling
INFO - Version - Hibernate Commons Annotations 3.1.0.GA
INFO - AnnotationConfiguration - Hibernate Validator not found: ignoring
INFO - notationSessionFactoryBean - Building new Hibernate SessionFactory
INFO - earchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO - ConnectionProviderFactory - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
INFO - SettingsFactory - RDBMS: MySQL, version: 5.5.16-log
INFO - SettingsFactory - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.21 ( Revision: ${bzr.revision-id} )
INFO - Dialect - Using dialect: org.hibernate.dialect.MySQLDialect
INFO - TransactionFactoryFactory - Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory
INFO - actionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
INFO - SettingsFactory - Automatic flush during beforeCompletion(): disabled
INFO - SettingsFactory - Automatic session close at end of transaction: disabled
INFO - SettingsFactory - JDBC batch size: 15
INFO - SettingsFactory - JDBC batch updates for versioned data: disabled
INFO - SettingsFactory - Scrollable result sets: enabled
INFO - SettingsFactory - JDBC3 getGeneratedKeys(): enabled
INFO - SettingsFactory - Connection release mode: auto
INFO - SettingsFactory - Maximum outer join fetch depth: 2
INFO - SettingsFactory - Default batch fetch size: 1
INFO - SettingsFactory - Generate SQL with comments: disabled
INFO - SettingsFactory - Order SQL updates by primary key: disabled
INFO - SettingsFactory - Order SQL inserts for batching: disabled
INFO - SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO - ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory
INFO - SettingsFactory - Query language substitutions: {}
INFO - SettingsFactory - JPA-QL strict compliance: disabled
INFO - SettingsFactory - Second-level cache: enabled
INFO - SettingsFactory - Query cache: disabled
INFO - SettingsFactory - Cache provider: org.hibernate.cache.EhCacheProvider
INFO - SettingsFactory - Optimize cache for minimal puts: disabled
INFO - SettingsFactory - Structured second-level cache entries: disabled
INFO - SettingsFactory - Echoing all SQL to stdout
INFO - SettingsFactory - Statistics: disabled
INFO - SettingsFactory - Deleted entity synthetic identifier rollback: disabled
INFO - SettingsFactory - Default entity-mode: pojo
INFO - SettingsFactory - Named query checking : enabled
INFO - SessionFactoryImpl - building session factory
WARN - ConfigurationFactory - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Users/CE_REAL/.m2/repository/net/sf/ehcache/ehcache/1.2.3/ehcache-1.2.3.jar!/ehcache-failsafe.xml
INFO - essionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured
INFO - SchemaExport - Running hbm2ddl schema export
INFO - SchemaExport - exporting generated schema to database
INFO - SchemaExport - schema export complete
INFO - ContextLoader - Root WebApplicationContext: initialization completed in 671 ms
INFO - ContextHandler - started o.e.j.w.WebAppContext{/,file:/C:/Users/CE_REAL/Documents/Development/media-database/src/main/webapp/},src/main/webapp
WARN - WebXmlFile - web.xml: No url-pattern found for 'filter' with name 'wicket-spring-hibernate'
INFO - WebXmlFile - web.xml: url mapping found for filter with name wicket-spring-hibernate:
WARN - WicketFilter - Unable to determine filter path from filter init-param, web.xml, or servlet 3.0 annotations. Assuming user will set filter path manually by calling setFilterPath(String)
INFO - Application - [wicket-spring-hibernate] init: Wicket core library initializer
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IBehaviorListener, method=public abstract void org.apache.wicket.behavior.IBehaviorListener.onRequest()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IFormSubmitListener, method=public abstract void org.apache.wicket.markup.html.form.IFormSubmitListener.onFormSubmitted()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=ILinkListener, method=public abstract void org.apache.wicket.markup.html.link.ILinkListener.onLinkClicked()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IOnChangeListener, method=public abstract void org.apache.wicket.markup.html.form.IOnChangeListener.onSelectionChanged()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IRedirectListener, method=public abstract void org.apache.wicket.IRedirectListener.onRedirect()]
INFO - RequestListenerInterface - registered listener interface [RequestListenerInterface name=IResourceListener, method=public abstract void org.apache.wicket.IResourceListener.onResourceRequested()]
INFO - Application - [wicket-spring-hibernate] init: Wicket extensions initializer
INFO - WebApplication - [wicket-spring-hibernate] Started Wicket version 6.2.0 in DEVELOPMENT mode
********************************************************************
*** WARNING: Wicket is running in DEVELOPMENT mode. ***
*** ^^^^^^^^^^^ ***
*** Do NOT deploy to your live server(s) without changing this. ***
*** See Application#getConfigurationType() for more information. ***
********************************************************************
INFO - WebXmlFile - web.xml: url mapping found for filter with name wicket.media-database: [/login/*]
INFO - Application - [wicket.media-database] init: Wicket core library initializer
INFO - Application - [wicket.media-database] init: Wicket extensions initializer
INFO - WebApplication - [wicket.media-database] Started Wicket version 6.2.0 in DEVELOPMENT mode
********************************************************************
*** WARNING: Wicket is running in DEVELOPMENT mode. ***
*** ^^^^^^^^^^^ ***
*** Do NOT deploy to your live server(s) without changing this. ***
*** See Application#getConfigurationType() for more information. ***
********************************************************************
INFO - AbstractConnector - Started SocketConnector#0.0.0.0:8080
INFO - SslContextFactory - Enabled Protocols [SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2] of [SSLv2Hello, SSLv3, TLSv1, TLSv1.1, TLSv1.2]
INFO - AbstractConnector - Started SslSocketConnector#0.0.0.0:8443
Edit :-
I tried renaming my User class to MediaUser and the #Table annotation to mediaUser to avoid problems with the USER word being reserved for some databases.
What I've found from the start up logging, as seen above, is that it does say it's running the export:
INFO - SchemaExport - Running hbm2ddl schema export
INFO - SchemaExport - exporting generated schema to database
INFO - SchemaExport - schema export complete
Also tried different approaches to the Hibernate annotations, like using other imports, #Table is now used by importing javax.persistence.Table, but I also tried the Hibernate org.hibernate.annotations.table, thus far without a solution to my problem.
I've found the answer to my problem, the annotations need either be set on the instance variables or on the class and it's methods and it needs to implement Serializable like:
#Entity
public class User implements Serializable {
#Id
#GeneratedValue
private Long id;
private String username;
private String password;
private String firstname;
private String lastname;
private Date birthDate;
private String email;
private String profileImage;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
// Getter and Setter methods
#Column
public getUsername() {
return username;
}
#Column
public getPassword() {
return password;
}
#Column
public getFirstname() {
return firstname;
}
#Column
public getLastname() {
return lastname;
}
#Column
#Temporal(TemporalType.TIME)
public getBirthDate() {
return birthDate;
}
#Column
public getEmail() {
return email;
}
#Column
public getProfileImage() {
return profileImage;
}
}
I had the same problem ... in my case, the problem was because the USER word is reserved for some data bases.
So, considering that your hibernate configuration files are right, just add a prefix in all your tables and the problem was solved.
I hope this solve your problem too =)
Try to use
#EntityScan({" yourentitypackagehere "})
in your springboot application
Related
I'm using Testcontainers 1.15.3 with Spring Boot 2.4 and Junit5.
When I run my test, testcontainers starts the first container and execute flyway scripts and then stop the first container. Immediatly a second container is started (without launching flyway scripts).
My test fail because the second container does not contain data.
Abstract class:
#ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
#TestPropertySource(locations = "classpath:application-test.properties")
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public abstract class AbstractIntegrationTest {
//...
}
Test class:
class ClassTest extends AbstractIntegrationTest{
#Test
void getById () throws Exception {
//...
}
}
Property file for test (jdbc url contains jdbc:tc to launch testcontainer):
spring.flyway.locations = classpath:database/structure,classpath:database/data
spring.datasource.url=jdbc:tc:postgresql:13.3:///databasename?TC_INITSCRIPT=file:src/test/resources/database/dataset/add_user.sql
Logs after launching test :
...
...
2021-06-21 12:56:52 [main] INFO 🐳 [postgres:13.3] - Creating container for image: postgres:13.3
2021-06-21 12:56:52 [main] INFO 🐳 [postgres:13.3] - Starting container with ID: 6a41054e8ec0f9045f8db9e945134234458a0e60b6157618f6f139cdf77d0cc4
2021-06-21 12:56:52 [main] INFO 🐳 [postgres:13.3] - Container postgres:13.3 is starting: 6a41054e8ec0f9045f8db9e945134234458a0e60b6157618f6f139cdf77d0cc4
...
...
2021-06-21 12:56:53 [main] INFO o.f.core.internal.command.DbMigrate - Migrating schema "public" to version "1.1.001 - init structure"
...
...
2021-06-21 12:56:55 [main] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2021-06-21 12:56:55 [main] INFO 🐳 [postgres:13.3] - Creating container for image: postgres:13.3
2021-06-21 12:56:55 [main] INFO 🐳 [postgres:13.3] - Starting container with ID: f02fccb0706f047918d849f897ce52bf41870a53821663b21212760c779db05f
2021-06-21 12:56:55 [main] INFO 🐳 [postgres:13.3] - Container postgres:13.3 is starting: f02fccb0706f047918d849f897ce52bf41870a53821663b21212760c779db05f
As we see in the logs above, two containers are created.
Could you help me to solve this problem ?
Thank you.
The way I fixed it is by adding ?TC_DAEMON=true to the datasource url.
(in my case I used postgis, so just replace it with jdbc:tc:postgresql:13.3
spring:
datasource:
driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
url: jdbc:tc:postgis:9.6-2.5:///dbname?TC_DAEMON=true
username: xxx
password: xxx
flyway:
enabled: true
locations: 'classpath:db/migration'
url: ${spring.datasource.url}
user: ${spring.datasource.username}
password: ${spring.datasource.password}
validate-on-migrate: true
I found a solution for my case: remove flyway user and password properties to use only spring ones. The duplication of these properties caused the double launch of the datasourse.
Before
spring:
flyway:
locations: [ classpath:flyway-scripts ]
user: xxx
password: xxx
datasource:
url: jdbc:postgresql://localhost:5432/postgres
username: xxx
password: xxx
After
spring:
flyway:
locations: [ classpath:flyway-scripts ]
datasource:
url: jdbc:postgresql://localhost:5432/postgres
username: xxx
password: xxx
Hi i am trying to insert a record in Mysql and get the ID of the inserted user in Spring boot JPA. i am getting following error. i have seen couple of questions like this but there they provided answer as USE JDBC Template for these kind of output. is it not possible to do it??. or this is related to some other issue.
Controller
#RequestMapping(value = "/signup", method = RequestMethod.POST)
public String createsignup(#RequestParam String name,#RequestParam String email,#RequestParam String password, ModelMap model) {
int userid = 0;
User user = new User(name,email);
userrepository.save(user);
userid = user.getId();
Authentication auth = new Authentication(email,password,userid);
authrepository.save(auth);
model.put("remember_token", auth.getRemember_token());
return "redirect:/profile";
}
Model
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String email;
private String location;
public User() {
}
}
Error
018-01-31 23:45:32.890 INFO 2512 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 7 ms
Hibernate: insert into user (email, location, name) values (?, ?, ?)
Hibernate: select next_val as id_val from hibernate_sequence for update
2018-01-31 23:45:41.783 ERROR 2512 --- [nio-8080-exec-2] o.hibernate.id.enhanced.TableStructure : could not read a hi value
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'blog.hibernate_sequence' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_45]
UPDATE
application properties
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
logging.level.org.springframework.web=INFO
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/blog
spring.datasource.username=pranava
spring.datasource.password=**********
This the message from server log
2018-02-01 22:21:29.691 INFO 5648 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.2.10.Final}
2018-02-01 22:21:29.693 INFO 5648 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-02-01 22:21:29.928 INFO 5648 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-02
After lot of search and try i found that User Table is default table in Postgresql. that's why it did not allowed. i have changed the table name and it worked. is there any other way is there to reuse it ?.
Make sure you have specified the correct dialect for hibernate and MySQL. It seems that value for identity column can't be set correctly.
For instance, if you use Spring Boot, check your application properties for something like:
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Or if you use Spring MVC without Spring Boot, that you have:
hibernateJpa.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
in LocalContainerEntityManagerFactoryBean configuration.
I have a spring boot app, it pulls in a jar which has two database configs, both mysql db's. Both databases look to be starting up correctly in the logs, but are not uniquely identified. It looks like default is registered and then reregistered so it appears to overwrite.
2017-07-19 10:24:16,817 INFO DriverManagerDataSource - Loaded JDBC driver: com.mysql.jdbc.Driver [tx-id=]
2017-07-19 10:24:16,937 INFO LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default' [tx-id=]
2017-07-19 10:24:16,947 INFO LogHelper - HHH000204: Processing PersistenceUnitInfo [
name: default
...] [tx-id=]
2017-07-19 10:24:16,991 INFO Version - HHH000412: Hibernate Core {5.0.12.Final} [tx-id=]
2017-07-19 10:24:16,992 INFO Environment - HHH000206: hibernate.properties not found [tx-id=]
2017-07-19 10:24:16,993 INFO Environment - HHH000021: Bytecode provider name : javassist [tx-id=]
2017-07-19 10:24:17,021 INFO Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final} [tx-id=]
2017-07-19 10:24:17,379 INFO Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect [tx-id=]
2017-07-19 10:24:17,593 WARN RootClass - HHH000038: Composite-id class does not override equals(): com.example.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:17,593 WARN RootClass - HHH000039: Composite-id class does not override hashCode(): com.example.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:17,943 INFO LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default' [tx-id=]
2017-07-19 10:24:17,970 INFO DriverManagerDataSource - Loaded JDBC driver: net.sourceforge.jtds.jdbc.Driver [tx-id=]
2017-07-19 10:24:17,972 INFO LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default' [tx-id=]
2017-07-19 10:24:17,972 INFO LogHelper - HHH000204: Processing PersistenceUnitInfo [
name: default
...] [tx-id=]
2017-07-19 10:24:18,370 INFO Dialect - HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect [tx-id=]
2017-07-19 10:24:18,389 INFO LobCreatorBuilderImpl - HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4 [tx-id=]
2017-07-19 10:24:18,394 WARN RootClass - HHH000038: Composite-id class does not override equals(): com.example.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:18,394 WARN RootClass - HHH000039: Composite-id class does not override hashCode(): com.example.entity.EmployeeGroupEntity$EmployeeGroupId [tx-id=]
2017-07-19 10:24:18,405 WARN EntityManagerFactoryRegistry - HHH000436: Entity manager factory name (default) is already registered. If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name' [tx-id=]
I have two classes for configuring the database connections, both of these are located in the imported jar, basically a common library.
#Configuration
#EnableTransactionManagement
#PropertySource(value = { "classpath:/${app.execution.environment}/application.properties" })
#EnableJpaRepositories(basePackages = "com.example", entityManagerFactoryRef = "mysqlEntityManager", transactionManagerRef = "mysqlTransactionManager")
#EntityScan(basePackages = { "com.example" })
public class MysqlHibernateConfig {
// beans configured here marked with #Primary
...
}
and
#Configuration
#EnableTransactionManagement
#PropertySource(value = { "classpath:/${app.execution.environment}/application.properties" })
#EnableJpaRepositories(basePackages = "com.example.another_package", entityManagerFactoryRef = "mysqlEntityManager2", transactionManagerRef = "mysqlTransactionManager2")
#EntityScan(basePackages = { "com.example.another_package" })
public class MysqlHibernateConfig2 {
...
}
I try to get data from each database through classes like this:
#Transactional("mysqlTransactionManager") // workspace complains about not being able to find this bean
#Service
public class PriceService {
}
#Transactional("mysqlTransactionManager2") // workspace complains about not being able to find this bean
#Service
public class PriceService2 {
}
PriceService gets data just fine, but PriceService2 tries to get data from mysqlTransactionManager instead of from mysqlTransactionManager2.
I also have the following classes to run my boot app:
#Configuration
#ComponentScan(basePackages = "com.example")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
//config stuff
}
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
How can I force one class to use a specific transaction manager/data source? I have been trying various configs and as far as I can tell this is set up correctly. If I put both of these datasource config classes into my spring boot app, I can connect to the correct datasources no problem. But when I move them to an outside library it does not work. I have to keep these in a common library because of the structure of my projects, two separate apps use this database config.
I do have the freedom to move the non primary db into my spring boot app if necessary, but that is not working either. Ends up with the same result.
21:20:26,958 INFO Version:15 - Hibernate Annotations 3.2.0.GA
21:20:26,976 INFO Environment:500 - Hibernate 3.2.1
21:20:26,981 INFO Environment:533 - hibernate.properties not found
21:20:26,983 INFO Environment:667 - Bytecode provider name : cglib
21:20:26,987 INFO Environment:584 - using JDK 1.4 java.sql.Timestamp handling
21:20:27,065 INFO Configuration:1423 - configuring from resource: hibernate.cfg.xml
21:20:27,066 INFO Configuration:1400 - Configuration resource: hibernate.cfg.xml
21:20:27,229 INFO Configuration:1538 - Configured SessionFactory: null
21:20:27,247 INFO Dialect:151 - Using dialect: org.hibernate.dialect.MySQLDialect
21:20:27,318 INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanyDetails
21:20:27,343 INFO EntityBinder:340 - Bind entity com.project1.model.CompanyDetails on table TAB_COMPANY_DETAILS
21:20:27,413 INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanyCategory
21:20:27,416 INFO EntityBinder:340 - Bind entity com.project1.model.CompanyCategory on table TAB_COMPANY_CATEGORY
21:20:27,419 INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanySector
21:20:27,420 INFO EntityBinder:340 - Bind entity com.project1.model.CompanySector on table TAB_COMPANY_SECTOR
21:20:27,426 INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.CompanyType
21:20:27,427 INFO EntityBinder:340 - Bind entity com.project1.model.CompanyType on table TAB_COMPANY_TYPE
21:20:27,430 INFO AnnotationBinder:387 - Binding entity from annotated class: com.project1.model.Country
21:20:27,430 INFO EntityBinder:340 - Bind entity com.project1.model.Country on table TAB_COUNTRY
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.generateDropSchemaScript(Configuration.java:756)
at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:93)
at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:61)
at com.project1.model.TestCompanyDetails.main(TestCompanyDetails.java:32)
I have the following repository:
public interface PlayerRealBalanceRepository extends JpaRepository<PlayerRealBalance, Long> {
#Modifying
#Query("update PlayerRealBalance balance set balance.balance = (balance.balance + ?1) where balance.id = ?2")
public void increaseBalance(long amount, long balanceId);
}
My Question - is this query thread safe? what if 2 concurrent queries like this are executed exactly at the same time? Do i have to use a lock method in order for it to work properly?
Thanks!
It will run into ACID(Atomicity, Consistency, Isolation, Durability) problem. Hence better to use transaction please refer spring transaction management here For your reference here is the log(self explanatory) what happens if you implement transaction management(though I use Mybatis)
2014-02-11 16:48:21,008 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Switching JDBC Connection [jdbc:oracle:thin] to manual commit
2014-02-11 16:48:21,013 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
2014-02-11 16:48:21,021 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,091 [main] DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [jdbc:oracle:thin:] will be managed by Spring
// does the db operation
2014-02-11 16:48:21,792 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,792 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Initiating transaction commit
2014-02-11 16:48:21,792 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Committing JDBC transaction on Connection [jdbc:oracle:thin:]
2014-02-11 16:48:21,792 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,792 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession#16a23cf]
2014-02-11 16:48:21,792 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Resetting isolation level of JDBC Connection [jdbc:oracle:thin:] to 2
2014-02-11 16:48:21,792 [main] DEBUG o.s.j.d.DataSourceTransactionManager - Releasing JDBC Connection [jdbc:oracle:thin:#] after transaction
2014-02-11 16:48:21,792 [main] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource