Using JPA in JavaFX environment - mysql

I'm trying to use JPA for handling persistence logic. For this I need, I suppose, persistence.xml, which looks like this:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="BookKeeperUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/Gamer"/>
<property name="hibernate.connection.username" value="UserName"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
then I need to import hibernate-entitymanager:4.3.5.Final to my library(using Intellij Idea as IDE) and the mysql driver. Which I also have done.
This is my entity class:
#Entity
#Table(name = "application_user")
public class ApplicationUser {
private String userName;
private String name;
private String passwordhHash;
#Id
#Column(name = "user_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "name_of_user")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "password_hash")
public String getPasswordhHash() {
return passwordhHash;
}
public void setPasswordhHash(String passwordhHash) {
this.passwordhHash = passwordhHash;
}
}
and the DAO class:
public class TestEntityManager {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("BookKeeperUnit");
EntityManager em = entityManagerFactory.createEntityManager();
public ApplicationUser getAppUserByUserName(String userName){
em.getTransaction().begin();
ApplicationUser appUser = em.find(ApplicationUser.class, userName);
em.getTransaction().commit();
em.close();
entityManagerFactory.close();
return appUser;
}
}
But I get an error that I don't really understand:
jul 08, 2014 8:57:35 EM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: BookKeeperUnit
...]
jul 08, 2014 8:57:35 EM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
jul 08, 2014 8:57:35 EM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
jul 08, 2014 8:57:35 EM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
jul 08, 2014 8:57:36 EM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
jul 08, 2014 8:57:36 EM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
jul 08, 2014 8:57:36 EM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/Gamer]
jul 08, 2014 8:57:36 EM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=UserName, password=****}
jul 08, 2014 8:57:36 EM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
jul 08, 2014 8:57:36 EM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
jul 08, 2014 8:57:36 EM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
jul 08, 2014 8:57:36 EM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;
at org.hibernate.cfg.annotations.EntityBinder.processComplementaryTableDefinitions(EntityBinder.java:936)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:824)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3788)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3742)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:78)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at appEntityManager.TestEntityManager.<init>(TestEntityManager.java:14)
at sample.Controller.<init>(Controller.java:13)
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 java.lang.Class.newInstance(Class.java:374)
at sun.reflect.misc.ReflectUtil.newInstance(ReflectUtil.java:49)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:731)
at
javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:775)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:180)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:563)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2348)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2164)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2061)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2778)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2757)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2743)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2730)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2719)
at sample.Main.start(Main.java:13)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
So how can I resolve the error?
java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;

Wow, after 3 days working on it I finally solved the problem. The main problem was that I was using the library hibernate-entitymanager:4.3.5.Final with java persistence API 2.0 instead of using it with hibernate-entitymanager:4.2.8.Final. I hope this will help others who may have same problem.

Related

404 Not Found:The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

This is the error I am getting I am using Gradle as build tool I have tried all the solutions
on internet
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name: Apache Tomcat/9.0.27
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Oct 7 2019 09:57:22 UTC
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.27.0
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Linux
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 5.0.0-32-generic
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: /usr/lib/jvm/java-8-openjdk-amd64/jre
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_222-8u222-b10-1ubuntu1~18.04.1-b10
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Private Build
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:
/home/sudarshan/work/.metadata/.plugins/org.eclipse.wst.server.core/tmp1
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: /home/sudarshan/Downloads/apache-tomcat-9.0.27
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -
Dcatalina.base=/home/sudarshan/work/.metadata/.plugins/org.eclipse.wst.server.core/tmp1
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/home/sudarshan/Downloads/apache-tomcat-9.0.27
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -
Dwtp.deploy=/home/sudarshan/work/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/
wtpwebapps
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/home/sudarshan/Downloads/apache-tomcat-
9.0.27/endorsed
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Oct 24, 2019 3:01:35 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in
production environments was not found on the java.library.path:
[/usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-
gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib]
Oct 24, 2019 3:01:35 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-2016"]
Oct 24, 2019 3:01:35 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Oct 24, 2019 3:01:35 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [549] milliseconds
Oct 24, 2019 3:01:35 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Oct 24, 2019 3:01:35 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.27]
Oct 24, 2019 3:01:36 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 24, 2019 3:01:37 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for
this logger for a complete list of JARs that were scanned but no TLDs were found in them.
Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Oct 24, 2019 3:01:37 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class
[org.springframework.web.context.ContextLoaderListener]
java.lang.NoClassDefFoundError:
Lorg/springframework/beans/factory/access/BeanFactoryReference;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
at java.lang.Class.getDeclaredFields(Class.java:1916)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:110)
at org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache
(DefaultInstanceManager.java:402)
at
org.apache.catalina.core.DefaultInstanceManager.newInstance
(DefaultInstanceManager.java:173)
at org.apache.catalina.core.DefaultInstanceManager.newInstance
(DefaultInstanceManager.java:151)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4607)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5146)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at
org.apache.tomcat.util.threads.InlineExecutorService.execute
(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute
(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:344)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:475)
Caused by: java.lang.ClassNotFoundException:
org.springframework.beans.factory.access.BeanFactoryReference
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1365)
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1188)
... 37 more
Oct 24, 2019 3:01:37 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Skipped installing application listeners due to previous error(s)
Oct 24, 2019 3:01:37 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: One or more listeners failed to start. Full details will be found in the appropriate
container log file
Oct 24, 2019 3:01:37 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/HibernateTemplate] startup failed due to previous errors
Oct 24, 2019 3:01:37 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 24, 2019 3:01:37 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for
this logger for a complete list of JARs that were scanned but no TLDs were found in them.
Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Oct 24, 2019 3:01:37 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Oct 24, 2019 3:01:37 PM org.springframework.web.context.ContextLoader
initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Oct 24, 2019 3:01:37 PM org.springframework.context.support.AbstractApplicationContext
prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Thu Oct 24 15:01:37 IST 2019];
root of context hierarchy
Oct 24, 2019 3:01:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-core-
config.xml]
Oct 24, 2019 3:01:38 PM org.springframework.web.context.ContextLoader
initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 188 ms
Oct 24, 2019 3:01:38 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springDispatcherServlet'
Oct 24, 2019 3:01:38 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'springDispatcherServlet': initialization started
Oct 24, 2019 3:01:38 PM org.springframework.context.support.AbstractApplicationContext
prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'springDispatcherServlet-servlet':
startup date [Thu Oct 24 15:01:38 IST 2019]; parent: Root WebApplicationContext
Oct 24, 2019 3:01:38 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-mvc-
config.xml]
Oct 24, 2019 3:01:38 PM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping
registerHandler
INFO: Root mapping to handler 'homeController'
Oct 24, 2019 3:01:38 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'springDispatcherServlet': initialization completed in 425 ms
Oct 24, 2019 3:01:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-2016"]
Oct 24, 2019 3:01:38 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 24, 2019 3:01:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [2,794] milliseconds
This is my build.gradle where I have added required dependencies
plugins {
// Apply the java-library plugin to add support for Java Library
id 'java-library'
id 'war'
id 'org.gretty' version '2.3.1'
}
repositories {
jcenter()
}
dependencies {
// This dependency is exported to consumers, that is to say found on their compile
classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile
classpath.
implementation 'com.google.guava:guava:28.0-jre'
// https://mvnrepository.com/artifact/org.springframework/spring-web
compile group: 'org.springframework', name: 'spring-web', version: '4.3.13.RELEASE'
// https://mvnrepository.com/artifact/org.springframework/spring-webmvc
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.14.RELEASE'
// https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1'
// https://mvnrepository.com/artifact/javax.servlet/jstl
compile group: 'javax.servlet', name: 'jstl', version: '1.2'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.13'
// https://mvnrepository.com/artifact/org.springframework/spring-jdbc
compile group: 'org.springframework', name: 'spring-jdbc', version: '5.1.5.RELEASE'
// https://mvnrepository.com/artifact/org.springframework/spring-beans
compile group: 'org.springframework', name: 'spring-beans', version: '5.1.5.RELEASE'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
}
This is my spring-core-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>
This is my spring-mvc-config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="HibernateTemplate"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/userdb"></property>
<property name="username" value="root"></property>
<property name="password" value="password"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="HibernateTemplate.StudentDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
This is my web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>web application</display-name>
<!-- The front controller of this Spring Web application, responsible for handling all
application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-core-config.xml</param-value>
</context-param>
</web-app>
This is my index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Add Employee
<!-- View Employees -->
</body>
</html>
studform.jsp file where I have created form to take values.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Add Employee
<!-- View Employees -->
</body>
</html>
index.jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Add Employee
<!-- View Employees -->
</body>
</html>
Student.java class
package HibernateTemplate;
public class Student {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
StudentController class
package HibernateTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import HibernateTemplate.Student;
import HibernateTemplate.StudentDao;
#Controller
public class StudentController {
#Autowired
StudentDao dao;
/*It displays a form to input data, here "command" is a reserved request attribute
which is used to display object data into form */
#RequestMapping("/studform")
public String showform(Model m){
m.addAttribute("command", new Student());
return "studform";
}
/*It saves object into database. The #ModelAttribute puts request data into model object.
*You need to mention RequestMethod.POST method
because default request is GET*/
#RequestMapping(value="/save",method = RequestMethod.POST)
public String save(#ModelAttribute("std") Student std){
dao.save(std);
return "save"; //will redirect to viewemp request mapping
}
}
StudentDao class
package HibernateTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Student s){
String sql="insert into student(id,name,email)
values('"+s.getId()+"',"+s.getName()+",'"+s.getEmail()+"')";
return template.update(sql);
}
}
I just needs to connect with database so that I can go ahead and do further operations, also
you can recommend me book where I can learn spring MVC using gradle as there is no gradle
stuff available on internet.
Try by removing this from <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> from <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">. I think this unnecessarily used. This may cause problem.
Updated bean should look like this :
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>

EJB/Hibernate does not access MySQL Database

I'm trying to learn how to work with JavaEE/EJB and database persistence, I have a basic example where I want to save a String to a database via input field and read the list of saved items.
I have a MySQL server installed on localhost (V5.7 Community Edition) and my test server is WildFly 10.1.0 (via Eclipse). The whole project is an EAR container containing a Web and EJB Subproject.
I am using container managed transactions, as I understand it, transactions are automatically created when a method is called and flushed/committed as soon as the method exits.
The problem is, that no data is ever written to the actual database. But no errors are thrown either. I assume, the entity manager caches all supposed saves and directly reads them back on select, without even checking the database. As such, when I restart the server, nothing remains. Also, when I look into mysql db directly, nothing is there either (even while wildfly server is running, directly after supposed insert). I also tried adding some rows to db table directly, but select does not "see" them either.
As a result, it seemed to me that the database is not even accessed, despite it being configured in the persistence.xml. I tried to remove connection url/username/password there and it actually made no difference, the entity manager still throws no errors and everything seems to work. So where exactly is it saving the data and what do I have to change so that it accesses the supplied mysql database instead?
Handler (in Web Project):
#ManagedBean(name = "handlerBean")
#SessionScoped
public class HandlerBean {
#EJB
private TodoWorkerBeanRemote worker;
private String input;
public void add() {
if (input.compareTo("") != 0) {
TodoBean item = new TodoBean();
item.setText(input);
worker.saveItem(item);
input = "";
}
}
...
Session Bean / Transaction container (in EJB project)
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class TodoWorkerBean implements TodoWorkerBeanRemote {
#PersistenceContext(unitName = "EnterpriseTestEJB")
private EntityManager entityManager;
public TodoWorkerBean() {
}
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) // does not help
public void saveItem(TodoBean item) {
// entityManager.joinTransaction(); <- does not help
entityManager.persist(item); // tried .merge() as well
// entityManager.flush(); <-does not help
}
...
Entity Bean (in EJB project)
#Entity
#Table(name = "todobean")
#NamedNativeQueries({
#NamedNativeQuery(name = "TodoBean.getItems", query = "select * from todobean", resultClass = TodoBean.class),
#NamedNativeQuery(name = "TodoBean.clearItems", query = "delete from todobean") })
public class TodoBean implements Serializable {
private Integer id;
private String text;
...
persistence.xml (tried with hibernate.cfg.xml as well, no difference)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="EnterpriseTestEJB">
<class>de.dianasalsa.ejb.TodoBean</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/feedback" /> // not used
<property name="hibernate.connection.username" value="root" /> // not used
<property name="hibernate.connection.password" value="root" /> // not used
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" /> // tried "create" as well
</properties>
</persistence-unit>
</persistence>
Log:
....
15:42:59,602 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 66) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'EnterpriseTest.ear/EnterpriseTestEJB.jar#EnterpriseTestEJB'
15:42:59,952 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 65) WFLYCLINF0002: Started client-mappings cache from ejb container
15:42:59,973 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 66) HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
15:43:00,102 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (ServerService Thread Pool -- 66) Envers integration enabled? : true
15:43:00,101 INFO [org.jboss.as.protocol] (management I/O-1) WFLYPRT0057: cancelled task by interrupting thread Thread[management-handler-thread - 3,5,management-handler-thread]
15:43:00,604 INFO [org.hibernate.tool.hbm2ddl.SchemaUpdate] (ServerService Thread Pool -- 66) HHH000228: Running hbm2ddl schema update
15:43:00,617 INFO [org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl] (ServerService Thread Pool -- 66) HHH000262: Table not found: todobean
15:43:00,619 INFO [org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl] (ServerService Thread Pool -- 66) HHH000262: Table not found: todobean
15:43:01,499 INFO [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 83) Mojarra 2.2.13.SP1 20160303-1204 für Kontext '/EnterpriseTestWeb' wird initialisiert.
15:43:02,379 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 83) WFLYUT0021: Registered web context: /EnterpriseTestWeb
15:43:02,414 INFO [org.jboss.as.server] (ServerService Thread Pool -- 34) WFLYSRV0010: Deployed "EnterpriseTest.ear" (runtime-name : "EnterpriseTest.ear")
15:43:02,515 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
15:43:02,519 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
15:43:02,519 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0025: WildFly Full 10.1.0.Final (WildFly Core 2.2.0.Final) started in 9581ms - Started 879 of 1127 services (422 services are lazy, passive or on-demand)
15:43:18,799 INFO [org.jboss.ejb.client] (default task-2) JBoss EJB Client version 2.1.4.Final
15:43:32,763 INFO [stdout] (default task-3) Hibernate:
15:43:32,763 INFO [stdout] (default task-3) /* insert de.dianasalsa.ejb.TodoBean
15:43:32,763 INFO [stdout] (default task-3) */ insert
15:43:32,763 INFO [stdout] (default task-3) into
15:43:32,763 INFO [stdout] (default task-3) todobean
15:43:32,763 INFO [stdout] (default task-3) (text)
15:43:32,763 INFO [stdout] (default task-3) values
15:43:32,764 INFO [stdout] (default task-3) (?)
15:43:32,786 INFO [stdout] (default task-3) Hibernate:
15:43:32,786 INFO [stdout] (default task-3) /* TodoBean.getItems */ select
15:43:32,786 INFO [stdout] (default task-3) *
15:43:32,787 INFO [stdout] (default task-3) from
15:43:32,787 INFO [stdout] (default task-3) todobean
sorry for my english...
you need to configure a JNDI name "jta-data-source", and say with "hibernate.hbm2ddl.auto" create new relations, like this example:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="EnterpriseTestEJB"
transaction-type="JTA">
<jta-data-source>java:jboss/datasources/some-name</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
wildfly has a "namesever" for that you work with the JNDI name to access from your annotation like "#PersistenceContext".
And in Wildfly at selfe you must configure a new MySql connection with that JNDI name.
For MySql connection download the jdbc driver and upload it to WildFly.
https://dev.mysql.com/downloads/connector/j/5.1.html
Inser MySqgl jdbc Driver
The connection will named with the JNDI name (java:jboss/datasources/some-name).
Add new MySql Connection (1)
Add new MySql Connection (2)
When you run your programm in Wildfly the programm will look over the JNDI name in wildfly for your MySql connection.
If you would like to look an example code i have one from my study here:
https://gitlab.com/Java_Project/JavaEE2.0
I'll hope it fixe your problem.

How to populate MySql db using hibernate?

I am starting with Hibernate by going through this Sample. But this is the information in the debug console and I think it has something to do with the configuration file because when the configure() method is called it throws an exception.
debug:
Feb 24, 2015 11:53:50 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Feb 24, 2015 11:53:50 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Feb 24, 2015 11:53:50 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 24, 2015 11:53:50 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 24, 2015 11:53:51 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
Feb 24, 2015 11:53:51 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Feb 24, 2015 11:53:51 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Feb 24, 2015 11:53:51 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: hibernate.hbm.xml
Feb 24, 2015 11:53:52 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Exception Thrown org.hibernate.InvalidMappingException: Unable to read XML
Exception in thread "main" java.lang.NullPointerException
at hellomain.main(hellomain.java:46)
Java Result: 1
BUILD SUCCESSFUL (total time: 15 seconds)
Main file:
public static void main(String[] args) {
Session session = null;
try
{
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sf = configuration.buildSessionFactory(sr);
session = sf.openSession();
session.beginTransaction();
System.out.println("Populating the Database.");
Message message = new Message("Hello Vinodh");
session.save(message);
session.getTransaction().commit();
System.out.println("DOne");
}catch(HibernateException e){
throw e;
}finally{
session.flush();
session.close();
}
}
Confg File:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="hibernate.connection.username">root</property>
<mapping resource="hibernate.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
Mapping File:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hello.Message" table="message">
<id name="id" column="id" type="Long">
<generator class="native"/>
</id>
<property name="text">
<column name="text"></column>
</property>
</class>
</hibernate-mapping>

Spring MVC + Hibernate not doing anything to the DB, no exceptions thrown

I'm at a loss for a solution. I've been playing with Spring MVC and Hibernate, and I had established a connection with my database, pulling data, no problem.
I added an #Entity, and maybe done some other changes, and now Hibernate won't do anything. By anything, I mean there is no SQL executed (as shown in the tomcat logs, using the show-sql option of hibernate). There is also no exceptions thrown at all, and Hibernate even tells me it has updated the DB schema (which it has not, since no tables have been created.).
I have checked that the getAllArticles() method gets called during runtime using a debugger.
I really don't know what to check now, if someone has any idea I'll be grateful forever.
My servlet config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:resources location="/resources/" mapping="/resources/**" />
<mvc:annotation-driven />
<context:component-scan base-package="com.last" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://10.0.0.2/lastDB" />
<property name="username" value="dbuser" />
<property name="password" value="dbpass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.test" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
The entity:
package com.last.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "ARTICLE")
public class Article {
private int id;
private String content;
private User author;
#Id
#GeneratedValue
#Column(name = "ARTICLE_ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "CONTENT", length=10000)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#ManyToOne
#Column(name="AUTHOR")
#JoinColumn(name = "USER_USER_ID")
public User getAuthor() {
return author;
}
public void setAuthor(User user) {
this.author = user;
}
}
The DAO:
package com.last.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.last.entities.Article;
import com.last.entities.User;
import com.last.exceptions.DAOException;
#SuppressWarnings("unchecked")
#Component
#Transactional(readOnly = true)
public class DAOImpl implements DAO {
#Autowired
SessionFactory sessionFactory;
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public List<User> getUserList() {
return currentSession().createCriteria(User.class).list();
}
#Override
public User getUserByID(int id) {
User result = (User) currentSession().createCriteria(User.class)
.add(Restrictions.eq("id", id)).uniqueResult();
if (result == null) {
throw new DAOException(DAOException.NO_RESULT);
} else {
return result;
}
}
#Override
public List<Article> getAllArticles() {
return currentSession().createCriteria(Article.class).list();
}
}
Tomcat's Log:
avr. 22, 2013 4:39:10 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0_15\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;D:\Programmes\LaTeX\MikTeX\miktex\bin;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Haskell\bin;D:\Programming Stuff\Haskell\2010.2.0.0\lib\extralibs\bin;D:\Programming Stuff\Haskell\2010.2.0.0\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\WIDCOMM\Bluetooth Software\syswow64;C:\Program Files (x86)\GTK2-Runtime\bin;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;D:\Programmes\PostgreSQL\bin;C:\Program Files\Calibre2\;F:\RailsInstaller\Git\cmd;F:\RailsInstaller\Ruby1.9.2\bin;D:\Programming Stuff\RailsInstaller\Git\cmd;D:\Programming Stuff\RailsInstaller\Ruby1.9.2\bin;F:\Web Server\wamp\ruby\bin;C:\Program Files\Java\jdk1.7.0_02\bin;D:\Programmes\NetBeans\ant\apache-ant-1.8.4\bin;C:\Program Files (x86)\OpenVPN\bin;.
avr. 22, 2013 4:39:11 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
avr. 22, 2013 4:39:11 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
avr. 22, 2013 4:39:11 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1055 ms
avr. 22, 2013 4:39:11 PM org.apache.catalina.core.StandardService startInternal
INFO: Démarrage du service Catalina
avr. 22, 2013 4:39:11 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.37
avr. 22, 2013 4:39:12 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [128] milliseconds.
avr. 22, 2013 4:39:12 PM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Déploiement du descripteur de configuration D:\Programming Stuff\Projects\FinalTest\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\conf\Catalina\localhost\Last.xml
avr. 22, 2013 4:39:12 PM org.apache.catalina.startup.SetContextPropertiesRule begin
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Last' did not find a matching property.
avr. 22, 2013 4:39:15 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
avr. 22, 2013 4:39:15 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
avr. 22, 2013 4:39:15 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
avr. 22, 2013 4:39:15 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Mon Apr 22 16:39:15 CEST 2013]; root of context hierarchy
avr. 22, 2013 4:39:15 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/last-servlet.xml]
avr. 22, 2013 4:39:16 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'dataSource' of type [class org.apache.commons.dbcp.BasicDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
avr. 22, 2013 4:39:16 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
avr. 22, 2013 4:39:16 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
avr. 22, 2013 4:39:16 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
avr. 22, 2013 4:39:16 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
avr. 22, 2013 4:39:17 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
avr. 22, 2013 4:39:17 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
avr. 22, 2013 4:39:17 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
avr. 22, 2013 4:39:17 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
avr. 22, 2013 4:39:17 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
avr. 22, 2013 4:39:17 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
avr. 22, 2013 4:39:17 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'sessionFactory' of type [class org.springframework.orm.hibernate4.LocalSessionFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
avr. 22, 2013 4:39:17 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1312f348: defining beans [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,mainController,DAOImpl,serviceImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,dataSource,sessionFactory,transactionManager,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
avr. 22, 2013 4:39:17 PM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
avr. 22, 2013 4:39:17 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.last.controllers.MainController.showHomePage(java.util.Map<java.lang.String, java.lang.Object>)
avr. 22, 2013 4:39:18 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource#6192fb7a] of Hibernate SessionFactory for HibernateTransactionManager
avr. 22, 2013 4:39:18 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 3389 ms
avr. 22, 2013 4:39:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'last'
avr. 22, 2013 4:39:18 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'last': initialization started
avr. 22, 2013 4:39:18 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'last-servlet': startup date [Mon Apr 22 16:39:18 CEST 2013]; parent: Root WebApplicationContext
avr. 22, 2013 4:39:18 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/last-servlet.xml]
avr. 22, 2013 4:39:18 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'dataSource' of type [class org.apache.commons.dbcp.BasicDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
avr. 22, 2013 4:39:18 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
avr. 22, 2013 4:39:18 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
avr. 22, 2013 4:39:18 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
avr. 22, 2013 4:39:18 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
avr. 22, 2013 4:39:18 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
avr. 22, 2013 4:39:18 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
avr. 22, 2013 4:39:18 PM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'sessionFactory' of type [class org.springframework.orm.hibernate4.LocalSessionFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
avr. 22, 2013 4:39:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1b2cc445: defining beans [org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,mainController,DAOImpl,serviceImpl,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0,dataSource,sessionFactory,transactionManager,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#1312f348
avr. 22, 2013 4:39:18 PM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
avr. 22, 2013 4:39:18 PM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping registerHandlerMethod
INFO: Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.last.controllers.MainController.showHomePage(java.util.Map<java.lang.String, java.lang.Object>)
avr. 22, 2013 4:39:18 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource#1583f012] of Hibernate SessionFactory for HibernateTransactionManager
avr. 22, 2013 4:39:19 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'last': initialization completed in 503 ms
avr. 22, 2013 4:39:19 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
avr. 22, 2013 4:39:19 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
avr. 22, 2013 4:39:19 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7587 ms
Thank you !
Could be copy-paste, but your hibernate session factory bean is scanning com.test for hibernate entities instead of com.last.

JPA + MySQL: After Timeout --> use a local Connection

as our connection is very unstable we have decided to switch to our local read-only database if a query times out.
But here is my problem: I do not get an exception when javax.persistence tries to query:
// Attribute
EntityManagerFactory entityManagerFactory;
EntityManager manager;
entityManagerFactory = Persistence
.createEntityManagerFactory("org.hibernate.tutorial.jpa");
manager = entityManagerFactory.createEntityManager();
try {
Query query = manager.createQuery(String.format(
"SELECT u FROM User u WHERE u.id = '%s'", 116));
User user = (User) query.getSingleResult();
manager.refresh(user);
System.out.println(user.getUsername());
} catch (org.hibernate.QueryTimeoutException ex) {
throw new QueryTimeoutException("timeout");
}
}
This is just a test to demonstrate my problem.
What am I missing?
Mysql: mysql-connector-java-5.1.16-bin.jar
JPA: javax.persistence_2.0.3.v201010191057.jar
Hibernate:
115 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
124 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.7.Final
126 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
129 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
132 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
208 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.6.7.Final
persistence.xml:
<properties>
<property name="hibernate.hbm2ddl.auto" value="valide"/>
<property name="hibernate.connection.url" value="jdbc:mysql:///database?zeroDateTimeBehavior=convertToNull"/>
<property name="hibernate.connection.username" value="user"/>
<property name="hibernate.connection.password" value="pass"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.query.timeout" value="1"/>
<property name="dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
Thank you
Tobias
Solution:
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://server/database", "user", "pass");
Every time I want to start a query I test if the Connection is alive:
if (connection.isValid(1)) {
return true;
} else {
throw new NoConnectionException();
You may not be seeing a timeout because some DBs don't support that feature.
"javax.persistence.query.timeout query timeout in milliseconds
(Integer or String), this is a hint used by Hibernate but requires
support by your underlying database."
See http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/configuration.html for more details.
I'd be inclined to switch to the read only all the time if you can't guarantee a reliable connection.