insert a data and get back ID in spring boot JPA - java

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.

Related

Hibernatre (jpa repository) - trying to fetch many-to-many relationship data

I'm currently learning Hibernate and I'm stuck at fetching data from many-to-many relationship in hibernate (spring-jpa). I'm trying to get data by id and it just doesn't work.
I know it's not realistic but one book can be taken from many persons.
The problem is, it does not matter in which class I put fetch type EAGER and in the second I put LAZY fetch type, it's throwing:
LazyInitializationException: failed to lazily initialize a collection of role
But if I put EAGER fetch type in both classes is throwing a StackOverFlowError.
The many-to-many logic goes like this we have a books in library and we have persons and many persons can take many books and book can be taken from many persons.
I have tried to put EAGER fetching in both classes but it gives me StackOverFlowError.
I have to mention that I'm using the JpaRepository interface.
The Person class:
#Entity
#Table(name = "persons")
public class Person { // (in library)
#Id
#Column(name = "id")
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#Column(name = "number_card")
private int numberCard;
#Column(name = "time_of_account_creating")
#Temporal(TemporalType.DATE)
private Date date;
#ManyToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
List<Book> books = new ArrayList<>();
public Person() {
this.date = new Date();
}
public Person(String name, int numberCard) {
this.name = name;
this.numberCard = numberCard;
this.date = new Date();
}
public void addBook(Book book) {
this.books.add(book);
}
// gettters and setters
The Book class:
#Entity
#Table(name = "books")
public class Book { // (in library)
#Id
#Column(name = "id")
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
#Column(name = "release_year")
private int releaseYear;
#Column(name = "name")
private String name;
#ManyToMany(mappedBy = "books", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private List<Person> persons = new ArrayList<>();
public Book() {
}
public Book(int releaseYear, String name) {
this.releaseYear = releaseYear;
this.name = name;
}
public List<Person> getPersons() {
return persons;
}
public void addPerson(Person person) {
this.persons.add(person);
}
// getters and setters
Main method in the #SpringBootApplication:
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(HibernateDemoApplication.class, args);
PersonRepository personRepository = context.getBean(PersonRepository.class);
System.out.println(personRepository.findById(4));
}
application.property:
spring.datasource.url = jdbc:mysql://localhost:3306/${DB}
spring.datasource.username = ${username}
spring.datasource.password = ${password}
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
The output console:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)
2020-03-26 15:59:27.228 INFO 18912 --- [ main] c.e.h.HibernateDemoApplication : Starting HibernateDemoApplication on abu with PID 18912 (/home/yoav/hibernateDemo/target/classes started by yoav in /home/yoav/hibernateDemo)
2020-03-26 15:59:27.232 INFO 18912 --- [ main] c.e.h.HibernateDemoApplication : No active profile set, falling back to default profiles: default
2020-03-26 15:59:28.450 INFO 18912 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-03-26 15:59:28.625 INFO 18912 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 131ms. Found 6 JPA repository interfaces.
2020-03-26 15:59:31.886 INFO 18912 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-26 15:59:31.928 INFO 18912 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-26 15:59:31.929 INFO 18912 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-26 15:59:32.101 INFO 18912 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-26 15:59:32.101 INFO 18912 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4687 ms
2020-03-26 15:59:32.636 INFO 18912 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-03-26 15:59:33.001 INFO 18912 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.12.Final
2020-03-26 15:59:33.631 INFO 18912 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-03-26 15:59:35.055 INFO 18912 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-03-26 15:59:37.374 INFO 18912 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-03-26 15:59:37.689 INFO 18912 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
Hibernate: alter table students add constraint FKrpifpqwvgu2pg2lib5c787vs foreign key (laptop_id) references laptops (id)
2020-03-26 15:59:41.092 INFO 18912 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-03-26 15:59:41.105 INFO 18912 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-03-26 15:59:42.982 WARN 18912 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-03-26 15:59:43.406 INFO 18912 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-26 15:59:44.775 INFO 18912 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-26 15:59:45.009 INFO 18912 --- [ main] c.e.h.HibernateDemoApplication : Started HibernateDemoApplication in 18.339 seconds (JVM running for 18.756)
Hibernate: select person0_.id as id1_5_0_, person0_.time_of_account_creating as time_of_2_5_0_, person0_.name as name3_5_0_, person0_.number_card as number_c4_5_0_, books1_.persons_id as persons_1_6_1_, book2_.id as books_id2_6_1_, book2_.id as id1_0_2_, book2_.name as name2_0_2_, book2_.release_year as release_3_0_2_ from persons person0_ left outer join persons_books books1_ on person0_.id=books1_.persons_id left outer join books book2_ on books1_.books_id=book2_.id where person0_.id=?
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.hibernateDemo.models.Book.persons, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:606)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)
at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:621)
at java.lang.String.valueOf(String.java:2994)
And I have to say it again, I am getting a StackOverFlowError if I put EAGER fetch type in both classes.
I know this thread is a few months old, but for asker in the future:
Issue:
You hide the Person#toString method. In the method you access the books field. It is fine since the fetchtype is EAGER. The issue is that you access the Book#toString where you access the persons field. This field is LAZY. Since you will not access this field within transaction you will always get the LazyInitializationException.
Solution:
Open a transaction. (google jpa transaction)
Load the entity.
Access the lazy fields. It will work!
Close the transaction: Note, all changes applied to loaded entities within transaction will be save to database automaticallay, there is no need to save them through repository DAO manually!

Spring Boot tries to close embedded database twice

I'm using an H2 embedded database for testing, and after the tests complete, I'm seeing the system trying to close the database twice and then it hangs waiting on the last log line shown here:
...
2019-07-14 07:58:47.115 INFO 44844 --- [ Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-07-14 07:58:47.115 INFO 44844 --- [ Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-07-14 07:58:47.116 INFO 44844 --- [ Thread-2] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2019-07-14 07:58:47.116 INFO 44844 --- [ Thread-4] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2019-07-14 07:58:47.117 INFO 44844 --- [ Thread-4] o.s.j.d.e.EmbeddedDatabaseFactory : Shutting down embedded database: url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false'
2019-07-14 07:58:47.117 INFO 44844 --- [ Thread-2] o.s.j.d.e.EmbeddedDatabaseFactory : Shutting down embedded database: url='jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false'
This is happening with Spring Boot 2.1.5 and 2.1.6
In the test class I set up the database this way
#RunWith(SpringRunner.class)
#SpringBootTest
#TestPropertySource(locations = "classpath:application.yml")
#Slf4j
public class DBTest {
...
static EmbeddedDatabase informixDB;
static JdbcTemplate informixJDBCTemplate;
#BeforeClass
public static void initDb() {
informixDB = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
informixJDBCTemplate = new JdbcTemplate(informixDB);
ClassPathResource initSchema = new ClassPathResource("data/informix/InformixUp.sql");
DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema);
DatabasePopulatorUtils.execute(databasePopulator, informixDB);
}
#AfterClass
public static void dropDb() {
ClassPathResource drop = new ClassPathResource("data/informix/InformixDown.sql");
DatabasePopulator databasePopulator = new ResourceDatabasePopulator(drop);
DatabasePopulatorUtils.execute(databasePopulator, informixDB);
}
I have this in my test/application.yml though it seems to be being ignored
spring:
jpa:
database-platform: org.hibernate.dialect.H2Dialect
h2:
console:
path: /h2-console
enabled: true
settings:
web-allow-others: true
# trace: true
datasource:
url: jdbc:h2:mem:informixDB;AUTO_SERVER=TRUE
username: sa
password:

#Transactional: Not committing at end of transaction; using Spring Boot and neo4j

I wanted to make use of #Transactional, expecting that annotated methods get a separate transaction which will be committed at the end of the method.
However, if I check the DB, there was nothing committed:
#Transactional
public boolean borrowLibraryItem(Long libraryUserId, Long uniqueLibraryItemNumber) {
boolean success = false;
LibraryUser borrower = libraryUserRepository.findByLibraryUserId(libraryUserId);
LibraryItem borrowItem = libraryItemRepository.findByUniqueLibraryItemNumber(uniqueLibraryItemNumber);
success = borrower != null && borrowItem != null;
if (success) {
BorrowedByRel borrowedByRel = new BorrowedByRel(borrower, borrowItem);
borrowedByRel.setBorrowDate(LocalDateTime.now());
borrowItem.setBorrowedByRel(borrowedByRel);
// libraryItemRepository.save(borrowItem);
}
return success;
}
The code commits the changes perfectly fine when using the repository.save-method, but not without.
Configuration is done via spring boot - as far as I understood, things should work out of the box this way (this might be the part where I got something wrong):
#SpringBootApplication
#EnableNeo4jRepositories(basePackages = "yalms.libraryapi.repositories")
#EntityScan("yalms.libraryapi.entities")
#EnableTransactionManagement
public class YalmsLibraryApplication {
public static void main(String[] args) {
SpringApplication.run(YalmsLibraryApplication.class, args);
}
}
Something regarding transactions seems to be happening, as the following logging.level.org.springframework.transaction.interceptor=TRACE shows:
Getting transaction for borrowLibraryItem()..
Don't need to create transaction for findByLibraryUserId, not transactional..
Request: MATCH (n:`LibraryUser`)..
Don't need to create transaction for findByUniqueLibraryItemNumber, not transactional..
Request: MATCH (n:`LibraryItem`)..
Completing transaction for borrowLibraryItem().
I would expect though that the changes (the addition of a relationship) would be committed. Am I misunderstanding something here or do I have something not configured right? Any help would be very much appreciated, thanks in advance!
UPDATE:
I've added a Neo4jTransactionManager-Bean as suggested in the comments, unfortunately it didn't help to solve my issue:
#Bean
public SessionFactory sessionFactory() {
org.neo4j.ogm.config.Configuration configuration = new org.neo4j.ogm.config.Configuration.Builder()
.uri(databaseUrl)
.credentials(userName, password)
.build();
return new SessionFactory(configuration,"yalms.libraryapi");
}
#Bean
public Neo4jTransactionManager transactionManager() {
return new Neo4jTransactionManager(sessionFactory());
}
I've enabled trace-output regarding everything coming from spring.data.*, and it's quite surprising to me as it seems that everything seems to be working fine:
TRACE 19634 --- [nio-8080-exec-2] .s.t.s.TransactionSynchronizationManager : Initializing transaction synchronization
TRACE 19634 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor : Getting transaction for [yalms.libraryapi.services.BorrowService.borrowLibraryItem]
TRACE 19634 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor : Don't need to create transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findByLibraryUserId]: This method isn't transactional.
DEBUG 19634 --- [nio-8080-exec-2] .s.d.n.r.q.d.DerivedGraphRepositoryQuery : Executing query for method findByLibraryUserId
TRACE 19634 --- [nio-8080-exec-2] .s.t.s.TransactionSynchronizationManager : Retrieved value [org.springframework.data.neo4j.transaction.SessionHolder#4adaed6] for key [org.neo4j.ogm.session.SessionFactory#5f4fecd0] bound to thread [http-nio-8080-exec-2]
INFO 19634 --- [nio-8080-exec-2] o.n.o.drivers.bolt.request.BoltRequest : Request: MATCH (n:`LibraryUser`) WHERE n.`libraryUserId` = { `libraryUserId_0` } WITH n RETURN n,[ [ (n)<-[r_b1:`BORROWED_BY`]-(l1:`LibraryItem`) | [ r_b1, l1 ] ] ], ID(n) with params {libraryUserId_0=0}
TRACE 19634 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor : Don't need to create transaction for [org.springframework.data.neo4j.repository.support.SimpleNeo4jRepository.findByUniqueLibraryItemNumber]: This method isn't transactional.
DEBUG 19634 --- [nio-8080-exec-2] .s.d.n.r.q.d.DerivedGraphRepositoryQuery : Executing query for method findByUniqueLibraryItemNumber
TRACE 19634 --- [nio-8080-exec-2] .s.t.s.TransactionSynchronizationManager : Retrieved value [org.springframework.data.neo4j.transaction.SessionHolder#4adaed6] for key [org.neo4j.ogm.session.SessionFactory#5f4fecd0] bound to thread [http-nio-8080-exec-2]
INFO 19634 --- [nio-8080-exec-2] o.n.o.drivers.bolt.request.BoltRequest : Request: MATCH (n:`LibraryItem`) WHERE n.`uniqueLibraryItemNumber` = { `uniqueLibraryItemNumber_0` } WITH n RETURN n,[ [ (n)-[r_b1:`BORROWED_BY`]->(l1:`LibraryUser`) | [ r_b1, l1 ] ] ], ID(n) with params {uniqueLibraryItemNumber_0=2}
TRACE 19634 --- [nio-8080-exec-2] o.s.t.i.TransactionInterceptor : Completing transaction for [yalms.libraryapi.services.BorrowService.borrowLibraryItem]
TRACE 19634 --- [nio-8080-exec-2] o.s.d.n.t.Neo4jTransactionManager : Triggering beforeCommit synchronization
TRACE 19634 --- [nio-8080-exec-2] o.s.d.n.t.Neo4jTransactionManager : Triggering beforeCompletion synchronization
DEBUG 19634 --- [nio-8080-exec-2] o.s.d.n.t.Neo4jTransactionManager : Initiating transaction commit
DEBUG 19634 --- [nio-8080-exec-2] o.s.d.n.t.Neo4jTransactionManager : Committing Neo4j OGM transaction [org.neo4j.ogm.drivers.bolt.transaction.BoltTransaction#5a5172dc] on Session [org.neo4j.ogm.session.Neo4jSession#7dc575ae]
TRACE 19634 --- [nio-8080-exec-2] o.s.d.n.t.Neo4jTransactionManager : Triggering afterCommit synchronization
TRACE 19634 --- [nio-8080-exec-2] .s.t.s.TransactionSynchronizationManager : Clearing transaction synchronization
TRACE 19634 --- [nio-8080-exec-2] o.s.d.n.t.Neo4jTransactionManager : Triggering afterCompletion synchronization
DEBUG 19634 --- [nio-8080-exec-2] o.s.d.n.t.Neo4jTransactionManager : Not closing pre-bound Neo4j Session after transaction
TRACE 19634 --- [nio-8080-exec-2] .s.t.s.TransactionSynchronizationManager : Removed value [org.springframework.data.neo4j.transaction.SessionHolder#4adaed6] for key [org.neo4j.ogm.session.SessionFactory#5f4fecd0] from thread [http-nio-8080-exec-2]
DEBUG 19634 --- [nio-8080-exec-2] o.s.d.n.w.s.OpenSessionInViewInterceptor : Closed Neo4j OGM Session in OpenSessionInViewInterceptor
But the update still does not end up in DB - makes kinda sense as there is no query that creates the new relation, but I do not understand why not: The retrieved entities seem to be attached to the transaction, the entities get modified within the transaction, so the changes should be committed once the transaction completes. Or did I misunderstand something here fundamentally?
Neo4j-OGM (the object graph mapper behind Spring Data Neo4j) needs an explicit save call. This is currently done by the explicit Spring Data Neo4j save call. There is no auto-commit when using Spring's transactional boundary.
Basically you have no error in your application and the explicit save call needs to be un-commented.
Some notes on the comments: You do not need to define a TransactionManager on your own within a Spring Boot applications. The spring-boot-starter-neo4j takes care of initialising Configuration, SessionFactory and an appropriate TransactionManager.

Spring boot jpa data using wrong database

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.

Hibernate does not generate table with annotations

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

Categories