Getting error "Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition" - spring

I'm getting the error:
Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
LoginController.java
#Controller
public class LoginController {
#Autowired
private RegisterDao dao;
#RequestMapping(value = "registerpage", method = RequestMethod.GET)
public ModelAndView getRegisterPage() {
System.out.println("control is in getRegister method");
return new ModelAndView("register", "reg", new Register());
}
#RequestMapping(value = "registeruser", method = RequestMethod.POST)
public ModelAndView registerUser(HttpServletRequest request) {
System.out.println("control is in registeruser method");
Register register = new Register();
register.setUname(request.getParameter("uname"));
register.setPassword(request.getParameter("password"));
register.setEmail(request.getParameter("email"));
register.setDob(request.getParameter("dob"));
register.setAge(request.getParameter("age"));
register.setCountry(request.getParameter("country"));
dao.addUser(register);
return new ModelAndView("success");
}
#RequestMapping(value = "delete", method = RequestMethod.GET)
public ModelAndView delete() {
return new ModelAndView("delete");
}
#RequestMapping(value = "deleteUser", method = RequestMethod.DELETE)
public void deleteUser(#RequestParam("uname") String uname, ModelMap map) {
Register register = new Register();
register.setUname(uname);
dao.deleteUser(register);
}
#RequestMapping(value = "readUsers", method = RequestMethod.GET)
public List<Register> usersList(ModelMap map) {
List<Register> register = dao.readUsers();
map.addAttribute("Users", register);
return register;
}
}
Register.java
`package com.spring.dao;
import java.util.List;
import com.spring.model.Register;
public interface RegisterDao {
public void addUser(Register register);
public List<Register> readUsers();
public void deleteUser(Register register);
}
Spring-servlet.xml
<context:component-scan base-package="com.spring" />
<mvc:annotation-driven />
<tx:annotation-driven />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.spring.model.Register</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="scott" />
<property name="password" value="tiger" />
</bean>
#Service
public class RegisterDaoImpl implements RegisterDao {
#Autowired
private HibernateTemplate template;
public void addUser(Register register,HttpServletRequest request,HttpServletResponse response) {
// TODO Auto-generated method stub
System.out.println("control is in adduser method of daoimpl");
template.saveOrUpdate(register);
}
public List<Register> readUsers() {
// TODO Auto-generated method stub
System.out.println("control is in readuser method of daoimpl");
List<Register> list = template.loadAll(Register.class);
return list;
}
public void deleteUser(Register register) {
// TODO Auto-generated method stub
System.out.println("control is in deleteuser method of daoimpl");
template.delete(register);
}
public void addUser(Register register) {
// TODO Auto-generated method stub
template.save(register);
}
}
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.spring</groupId>
<artifactId>RegistrationWithSpringMvc</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>RegistrationWithSpringMvc</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.hynnet/oracle-driver-ojdbc6 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.2.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.0.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>

Add method setTemplate() and setCheckWriteOperation(false) for template inside your RegisterDAOImpl.
public void setTemplate(HibernateTemplate template) {
template.setCheckWriteOperations(false);
this.template = template;
}

Related

java.lang.NoSuchMethodError: org.springframework.core.io.ResourceEditor

I am trying to create spring application. I am getting below error during starting the tomcat server. Can anyone please help me to find out the reason for this issue?
exception
May 03, 2016 12:01:27 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [cricketapp] in web application [/CricketApp] threw load() exception
java.lang.NoSuchMethodError: org.springframework.core.io.ResourceEditor.<init>(Lorg/springframework/core/io/ResourceLoader;Lorg/springframework/core/env/PropertyResolver;)V
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5318)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5610)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1572)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1562)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CricketApp</groupId>
<artifactId>CricketApp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.0-Final</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.0-Final</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.codehaus.openxma</groupId>
<artifactId>dsl-platform</artifactId>
<version>3.6.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>1.0.0.Final</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</project>
my spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="com.cricketapp" />
<mvc:resources mapping="/resources/**" location="/resources/**" />
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.cricketapp.domain" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />
<context:spring-configured />
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/cricketapp" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
You should check your dependencies. One problem is your spring-test dependency: it has an old incompatible version and it is not in scope test!
The ResourceEditorchanged between 2.5 and 4.2, the old constructor ResourceEditor(ResourceLoader) is no longer available but instead ResourceEditor(ResourceLoader,PropertyResolver).
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.5.RELEASE</version>
<scope>test</scope>
</dependency>
In your current setup I would assume you will have two versions of Spring framework (2.5 and 4.2.5) in your dependencies. Have a look using mvn dependency:tree before and after changing the spring-test dependency above.
If you have a doupt on your dependecies, I recommand to build a web project skeleton from https://start.spring.io/, import it to your workspace and check the Dependency Hiearchy tab of your pom.xml.
See the example: inputs to generate a spring mvc 4.2.5 tomcat 7 project test, hibernate... are included
The configs, even your web.xml are initialized by annotations. you can avoid the spring-servlet by initializing through annotation,
Exmanple Hibernate:
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.yourpackage.configuration" })
#PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {``
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.yourpackage.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
For the viewResolver:
#Configuration
#ComponentScan(basePackages="com.yourpackage")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Use the Dependency Hiearchy as a reference to be sure you're not missing any dependency.
For tomcat you can omit the dependecies since you have your localown server.

Error: org.apache.jasper.JasperException: Unable to compile class for JSP, How fix it?

I encouter following error:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 8 in the jsp file: /student/StudentError.jsp
The method println6(String) is undefined for the type PrintStream
5: <p><b>Stack trace:</b></p>
6: <%
7: Exception exp = (Exception)request.getAttribute("javax.servlet.error.exception");
8: System.out.println6(exp.getMessage()+"<br/>");
9: StackTraceElement [] elements = exp.getStackTrace();
10: for(int i=0;i<elements.length;i++){
11: System.out.println(elements[i].toString()+"<br/>");
Stacktrace:
at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:199)
at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:446)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:361)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:405)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:349)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:801)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:595)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1126)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1060)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:200)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:75)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1217)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1005)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:801)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1126)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1060)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:113)
at org.eclipse.jetty.server.Server.handle(Server.java:509)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:288)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:240)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:539)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)
at java.lang.Thread.run(Thread.java:745)
Here file JavaClazzWeb-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
<!-- <bean id="xsltViewResolver" class="org.springframework.web.servlet.view.xslt.XsltViewResolver">
<property name="order" value="1"/> <property name="viewClass" value ="org.springframework.web.servlet.view.xslt.XsltView"/>
<property name="sourceKey" value="data"/> <property name="suffix" value=".xsl"/>
<property name="prefix" value="/xsl/"/> </bean> <bean id="studentDAO" class="edu.java.spring.dao.StudentDAO">
<property name="dataSource" ref="dataSource"/> <property name ="insertSQL"
value="insert into student(name,age) values(?,?)"/> </bean> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject"> <ref bean="studentDAO" /> </property> <property
name="targetMethod"> <value>createTableIfNotExist</value> </property> <property
name="arguments"> <list> <value>student</value> <value>create table student(
id bigint primary key generated always as identity(start with 1,increment
by 1), name varchar(1000), age integer ) </value> </list> </property> </bean> -->
<context:component-scan base-package="edu.java.spring.controller" />
<mvc:annotation-driven />
<mvc:resources location="/avatar/" mapping="/avatar/**" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="3" />
<property name="suffix" value=".jsp" />
<property name="prefix" value="/student/" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000"></property>
</bean>
<bean id="xsltViewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="order" value="2" />
<property name="basename" value="views" />
</bean>
<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="order" value="1" />
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles/definitions.xml</value>
</list>
</property>
</bean>
<bean id="studentDao" class="edu.java.spring.dao.impl.StudentHibernateDaoImpl" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="edu.java.spring.model" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url"
value="jdbc:derby:D:\PROJECTSPRING\studentdb;create=true" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">StudentError</prop>
</props>
</property>
</bean>
<bean id="studentMapper" class="edu.java.spring.model.StudentMapper" />
</beans>
Here file StudentController
#Controller
public class StudentController {
// #RequestMapping(value = "/student/add", method = RequestMethod.POST)
// public String addStudent(#Valid Student student,ModelMap model){
// model.addAttribute("name", student.getName());
// model.addAttribute("age", student.getAge());
// return "StudentView";
// }
#RequestMapping(value="/student/form",method = RequestMethod.GET )
public ModelAndView student(){
return new ModelAndView("StudentForm", "command", new Student());
}
#Autowired
public StudentHibernateDaoImpl studentDAO;
Here file Class StudentHibernateDaoImpl
public class StudentHibernateDaoImpl implements StudentDAO {
#Autowired
public LocalSessionFactoryBean sessionFactory;
#Override
public void shutdown() {
// TODO Auto-generated method stub
}
#Override
public void insert(Student student) {
// TODO Auto-generated method stub
}
#Override
public List<Student> listStudents() {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
Query query = (Query) session.createQuery("from Student");
try {
return (List<Student>)query.getResultList();
} finally {
// TODO: handle finally clause
session.close();
}
}
Here file Class StudentDao
public interface StudentDAO {
public void shutdown();
public void insert(Student student);
public List<Student> listStudents();
public Student loadStudent(int id);
public void update(Student student);
public void delete(Integer id);
public List<Student> searchStudent(String name);
}
Here file POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.java.spring</groupId>
<artifactId>springDAT-MVC</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springDAT-MVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.12.1.1</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-extras</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>springDAT-MVC</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<skipTests>true</skipTests>
<argLine>-Xmx2524m</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<fork>true</fork>
<compilerArgs>
<arg>-XDignore.symbol.file</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.0.M1</version>
<configuration>
<jvmArgs>-Xmx1048m -Xms536m
-XX:PermSize=128m -XX:MaxPermSize=512m</jvmArgs>
<reload>manual</reload>
<systemProperties>
<systemProperty>
<name>lib</name>
<value>${basedir}/target/spring-mvc/WEB-INF/lib</value>
</systemProperty>
</systemProperties>
<scanIntervalSeconds>3</scanIntervalSeconds>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
<contextPath>/</contextPath>
<webAppSourceDirectory>${basedir}/src/main/webapp</webAppSourceDirectory>
<webXml>${basedir}/src/main/webapp/WEB-INF/web.xml</webXml>
<classesDirectory>${basedir}/target/classes</classesDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
Here file Student
package edu.java.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.Range;
#XmlRootElement(name="item")
#Entity
#Table(name = "student",uniqueConstraints={#UniqueConstraint(columnNames="Id")})
public class Student {
// #NotBlank
// #Size(min=2,max=100,message ="Age value is invalid")
private String name;
private int id;
// #Range(min=1,max=150)
private int age;
#XmlAttribute
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name ="id", unique=true,nullable =false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
#Column(name = "Name",nullable = false,length = 200)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
#Column(name = "age",nullable = false)
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Answer to your question
From effective Spring 2.5.x versions, have a concept of stereotyped Annotations you have to mark to your classes with these annotations to make it eligible for component scanning.
In your case you have mark your DAOImpl class with #Repository annotation like this given below.
#Repository
public class StudentHibernateDaoImpl implements StudentDAO {
Change your component scan tag as
<context:component-scan
base-package="edu.java.spring.controller,yourPackage.StudentHibernateDaoImpl"/> >
Here is an example which will resolve your issue.

Spring 4 + hibernate 4 - HibernateException: No Session found for current thread

I've read all of the other questions/answers about this issue but still missing something for me. Can anyone help?
I've found that <prop key="hibernate.current_session_context_class">thread</prop> partially works but it seams that it's not the spring current session so i commented it (if I use it, it will give this: HibernateException: get is not valid without active transaction).
pom.xml
<properties>
<!-- Spring -->
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.3.5.Final</hibernate.version>
<spring-data-jpa.version>1.5.2.RELEASE</spring-data-jpa.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- Java Persistence API -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
</dependencies>
application-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="org.portal" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- DATABASE -->
<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://admin#127.0.0.1::3306" />
<property name="username" value="admin" />
<property name="password" value="admin" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>org.portal.user.User</value>
<value>org.portal.user.role.Role</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userService" class="org.portal.user.UserServiceImpl">
<property name="userRepository" ref="userRepository"/>
</bean>
<bean id="userRepository" class="org.portal.user.UserRepositoryImpl"/>
</beans>
User.java
#Entity
#Table(name="user")
public class User {
#Column(name = "email", nullable = false)
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserServiceImpl.java
#Service
class UserServiceImpl implements UserService, UserDetailsService {
#Autowired
private UserRepository userRepository;
#Transactional
public org.portal.user.User getUserByEmail(String email) {
org.portal.user.User user = userRepository.getUserByEmail(email);
return user;
}
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
org.portal.user.User user = getUserByEmail(email);
}
}
UserRepositoryImpl.java
#Repository
class UserRepositoryImpl implements UserRepository {
#Autowired
private SessionFactory sessionFactory;
public User getUserByEmail(String email) {
return (User) sessionFactory.getCurrentSession().get(User.class, email);
}
}
In your code loadUserByUsername (which is not #Transactional) invokes getUserByEmail. Although it's marked #Transactional, the annotation (proxying) will not take effect because both methods belong to same class. In most cases the best is to mark whole #Service class with #Transactional annotation.

Spring #Autowired now work with #Component class

In my JavaFX stand alone application, it will get null value when I #Autowired some Service class to JavaFX Controller (with #Component annotation). My code is as below and some one can please help me. Thanks a lot.
Dao Class
package com.core.repository;
public interface DeviceDao extends PagingAndSortingRepository<Device, Integer>, JpaSpecificationExecutor<Device> {
Device findById(Integer id);
Device findByName(String name);
List<Device> findAll();
}
Service class
package com.core.service.impl;
#Service("deviceService")
public class DeviceServiceImpl implements DeviceService {
#Autowired
private DeviceDao deviceDao;
public List<Device> selectAll() {
return deviceDao.findAll();
}
}
JavaFX Controller with #Component annotation
package com.stportal.ui.contoller;
#Component
public class HomeController implements Initializable {
#Autowired
private DeviceService deviceService;
#Override
public void initialize(URL url, ResourceBundle rb) {
// This condition will not execute due to service was null
if(deviceService != null) {
System.out.println("Not Null");
}
}
}
application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
">
<context:component-scan base-package="com" />
<context:annotation-config/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
<property name="packagesToScan" value="com.core.domain" />
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<!--dialect for MySQL Server-->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!--<prop key="hibernate.hbm2ddl.auto">create</prop>-->
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
</props>
</property>
</bean>
<bean id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
<jpa:repositories base-package="com"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
<context:property-placeholder
ignore-resource-not-found="true" location="classpath*:/project.properties" />
<!-- DataSource Related Configurations -->
<beans:bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!--configuration pool via c3p0-->
<beans:property name="driverClass" value="${jdbc.driver}"/>
<beans:property name="jdbcUrl" value="${jdbc.url}"/>
<beans:property name="user" value="${jdbc.username}"/>
<beans:property name="password" value="${jdbc.password}"/>
<beans:property name="description" value="integration_ds"/>
<!--seconds -->
<beans:property name="acquireIncrement" value="${datasource.acquireIncrement}"/>
<beans:property name="idleConnectionTestPeriod" value="${datasource.idleConnectionTestPeriod}"/>
<!--configuration pool via c3p0-->
<beans:property name="maxPoolSize" value="${datasource.maxPoolSize}"/>
<beans:property name="maxStatements" value="${datasource.maxStatements}"/>
<beans:property name="minPoolSize" value="${datasource.minPoolSize}"/>
<beans:property name="initialPoolSize" value="${datasource.initialPoolSize}"/>
<beans:property name="maxIdleTime" value="${datasource.maxIdleTime}"/>
<beans:property name="acquireRetryAttempts" value="${datasource.acquireRetryAttempts}"/>
<beans:property name="acquireRetryDelay" value="${datasource.acquireRetryDelay}"/>
<beans:property name="breakAfterAcquireFailure" value="${datasource.breakAfterAcquireFailure}"/>
</beans:bean>
</beans>
Maven pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Configure module specific parameters -->
<groupId>com</groupId>
<artifactId>IDEW</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>IDEW</name>
<url>http://maven.apache.org</url>
<!-- Configure dependency specific properties -->
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.0.2.RELEASE</org.springframework-version>
<spring.version>4.0.2.RELEASE</spring.version>
<hibernate.version>4.3.1.Final</hibernate.version>
<aspectj.version>1.7.3</aspectj.version>
<spring-data-jpa.version>1.4.2.RELEASE</spring-data-jpa.version>
<hibernate-validator.version>5.0.2.Final</hibernate-validator.version>
<slf4j.version>1.7.5</slf4j.version>
<logback.version>1.1.0</logback.version>
<commons-lang3.version>3.2.1</commons-lang3.version>
<commons-io.version>2.4</commons-io.version>
<junit.version>4.11</junit.version>
<ehcache.version>2.6.8</ehcache.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- Configure all dependencies -->
<dependencies>
<!-- JavaFX -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>javafx</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>${java.home}/lib/jfxrt.jar</systemPath>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- CGLIB (required for Spring annotation configuration) -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
<!-- Build specific configurations -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<fork>true</fork>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<classpathScope>compile</classpathScope>
<mainClass>com.stportal.app.MainApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
I know little about Spring, but Koen Serneels wrote a nice blog on Spring and JavaFX integration. The magic key to getting the dependency injection in Spring to work together with JavaFX controllers is to set a controller factory on the FXMLLoader.
Here is a quick sketch of the relevant loading code using Java 8 syntax (I haven't tested it as I don't use Spring - if it doesn't work, please edit the post and correct it if you can).
import java.io.*;
import javafx.fxml.FXMLLoader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringFxmlLoader {
private static final ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(
SpringApplicationConfig.class
);
public Object load(String url) throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setControllerFactory(
(clazz) -> applicationContext.getBean(clazz)
);
return loader.load(
SpringFxmlLoader.class.getResourceAsStream(url)
);
}
}
Even it was not #Autowired, it was fine when I get that service form the Application context.
#Component
public class HomeController implements Initializable {
private DeviceService deviceService;
#Override
public void initialize(URL url, ResourceBundle rb) {
deviceService = AppUtil.appContext.getBean(DeviceService.class);
// Now this condition is execute due to service was NOT null
if(deviceService != null) {
System.out.println("Not Null");
}
}
}

Spring error (org.springframework.beans.factory.BeanCreationException)

Im new using Spring, and I have a problem when run my webbapp. Im using a Jboss Server and NetBeans
It's the error:
13:07:19,692 ERROR [ContextLoader] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.atlantis.atencioncliente.service.impl.HibernateDao.setSessionFactory(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [persistence-beans.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.slf4j.impl.StaticLoggerBinder.getSingleton()Lorg/slf4j/impl/StaticLoggerBinder;
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
FOLLOW THE ERROR
Here the employeeDao interface:
package com.atlantis.atencioncliente.service.dao;
import com.atlantis.atencioncliente.domain.Employee;
import com.atlantis.atencioncliente.service.GenericDao;
/**
* DAO of employee.
*/
public interface EmployeeDao extends GenericDao<Employee, Long> {
/**
* Tries to remove employee from the system.
* #param employee Employee to remove
* #return {#code true} if employee is not assigned to any task
* or timesheet. Else {#code false}.
*/
boolean removeEmployee(Employee employee);
}
Here Hibernate.dao
package com.atlantis.atencioncliente.service.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.atlantis.atencioncliente.service.GenericDao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
/**
* Basic DAO operations dependent with Hibernate's specific classes
* #see SessionFactory
*/
#Transactional(propagation= Propagation.REQUIRED, readOnly=false)
public class HibernateDao<E, K extends Serializable> implements GenericDao<E, K> {
private SessionFactory sessionFactory;
protected Class<? extends E> daoType;
public HibernateDao() {
daoType = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void add(E entity) {
currentSession().save(entity);
}
#Override
public void update(E entity) {
currentSession().saveOrUpdate(entity);
}
#Override
public void remove(E entity) {
currentSession().delete(entity);
}
#Override
public E find(K key) {
return (E) currentSession().get(daoType, key);
}
#Override
public List<E> list() {
return currentSession().createCriteria(daoType).list();
}
}
And here persistence-bean.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- we can use annotations -->
<context:annotation-config />
<!-- package to look for annotated classes -->
<context:component-scan base-package="com.atlantis.atencioncliente.service.impl" />
<!-- we will manage transactions with annotations -->
<tx:annotation-driven />
<!-- data source for our database -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
<property name="url" value="jdbc:mysql://SBPORTALPRE/atclientepre" />
<property name="username" value="atcliuser" />
<property name="password" value="atclipass" />
</bean>
<!-- configure hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses" >
<list>
<value>com.atlantis.atencioncliente.domain.Employee</value>
<value>com.atlantis.atencioncliente.domain.Manager</value>
<value>com.atlantis.atencioncliente.domain.Task</value>
<value>com.atlantis.atencioncliente.domain.Timesheet</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg type="javax.sql.DataSource" ref="dataSource"/>
</bean>
</beans>
Finally, here is my pom.XML:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.atlantis</groupId>
<artifactId>com.atlantis</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>atencioncliente</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.8.Final</version>
<exclusions>
<exclusion>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j
-->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
Any suggest? Thanks!

Resources