Spring security No Hibernate Session bound to thread - java

I searched the forum for this answer, but i could not find a solution.
I have configured my transaction manger bean
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
I have configured my session factory.
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="url" value="jdbc:derby://localhost:1527/hibernate"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>org.krams.tutorial.domain.Person</value>
<value>org.krams.tutorial.domain.UserRole</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
My daoImpl and Service class have #repository and #transactional tag
#Repository("personDao")
public class PersonDAOImpl implements PersonDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void savePerson(Person person) {
sessionFactory.getCurrentSession().saveOrUpdate (person);
}
#Override
public Person findByName(String name){
String query = "select * from Person p where p.username='"+name+"'";
Person person = (Person) sessionFactory.getCurrentSession().createQuery(query);
return person;
}
}
#Service("userService")
#Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class PersonServiceImpl implements PersonService{
#Autowired
private PersonDAO personDao;
#Override
#Transactional(propagation=Propagation.SUPPORTS, readOnly=false)
public void savePerson(Person person) {
personDao.savePerson(person);
}
#Override
#Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public Person findByName(String name){
return personDao.findByName(name);
}
}
I have one more service class for Spring Security database implementation
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private PersonService userService;
#Autowired
private Assembler assembler;
#Transactional(readOnly = true)
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
try {
Person person = userService.findByName(username);
return (UserDetails) assembler.buildUserFromUserEntity(person);
} catch (NoResultException e) {
throw new UsernameNotFoundException(e.getLocalizedMessage());
}
}
}
stacktrace:
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544)
at org.krams.tutorial.dao.PersonDAOImpl.findByName(PersonDAOImpl.java:30)
at org.krams.tutorial.service.PersonServiceImpl.findByName(PersonServiceImpl.java:40)
at org.krams.tutorial.service.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:37)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:82)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:124)
at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:120)
at org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:48)
at org.springframework.security.authentication.ProviderManager.doAuthentication(ProviderManager.java:138)
at org.springframework.security.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:48)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:97)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
I am confused as where did i go wrong. Please guys help me out.

Looks like you have missed to enable the transaction support.
Add tx:annotation-driven to the configuration:
<beans
...
xmlns:tx="http://www.springframework.org/schema/tx"
...
xsi:schemaLocation="...
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
...
<tx:annotation-driven transaction-manager="transactionManager" />

Related

Spring #Resource null pointer exception

I'm creating a Spring MVC application. And I have a Basket bean that has few autowired beans in in.
#Component
public class Basket {
#Autowired
#Qualifier("CPContainer")
private CPContainer cpContainer;
#Autowired
#Qualifier("FBContainer")
private FBContainer fbContainer;
public CPContainer getCpContainer() {
return cpContainer;
}
public void setCpContainer(CPContainer cpContainer) {
this.cpContainer = cpContainer;
}
public FBContainer getFbContainer() {
return fbContainer;
}
public void setFbContainer(FBContainer fbContainer) {
this.fbContainer = fbContainer;
}
Autowired beans CPContainer and FBContainer have List inside of them wired with list in dispather-servltet.xml via #Resource annotation:
#Component
public class FBContainer implements Container {
#Resource(name = "FBList")
private List<FBProduct> products;
private int id;
private int amount;
#Override
public List<FBProduct> getProducts() {
return products;
}
#Override
public FBProduct getProductById(int id) {
return products.get(id);
}
dispatcher-servltet.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans ...
<mvc:annotation-driven/>
<context:component-scan base-package="com.concrete"/>
<util:list id="FBList" value-type="com.concrete.pojo.product.FBProduct">
<bean id="fb1" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="0"/>
<property name="mass" value="1000"/>
<property name="l" value="8980"/>
<property name="b" value="1490"/>
<property name="h" value="220"/>
</bean>
<bean id="fb2" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="1"/>
<property name="mass" value="2000"/>
<property name="l" value="8980"/>
<property name="b" value="1190"/>
<property name="h" value="220"/>
</bean>
<bean id="fb3" class="com.concrete.pojo.product.FBProduct">
<property name="id" value="2"/>
<property name="mass" value="3000"/>
<property name="l" value="7180"/>
<property name="b" value="1490"/>
<property name="h" value="220"/>
</bean>
</util:list>
<bean id="FBContainer" class="com.concrete.pojo.container.FBContainer">
<property name="products" ref="FBList"/>
</bean>
<bean id="CPContainer" class="com.concrete.pojo.container.CPContainer">
<property name="products" ref="CPList"/>
</bean>
</beans>
I'm adding Basket class to a model as model attribute, wich I intend to use in jsp page to get data from Container's List(Like FBProducts in FBContainer). But when i try to access a List I get null pointer exception :
java.lang.NullPointerException
com.concrete.pojo.container.FBContainer.getProductById(FBContainer.java:25)
com.concrete.pojo.container.Basket.calculateMass(Basket.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
org.apache.jasper.el.JasperELResolver.invoke(JasperELResolver.java:139)
org.apache.el.parser.AstValue.getValue(AstValue.java:174)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:950)
org.apache.jsp.calculate_jsp._jspService(calculate_jsp.java:93)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
MainController.class :
#Controller
public class MainController {
#Autowired
#Qualifier("basket")
private Basket basket;
#RequestMapping(value = "/calculate",method = RequestMethod.POST)
public String calculate(Model model,Basket basket){
model.addAttribute("Basket",basket);
return "calculate";
}
}
I think i found the solution. It appears I was adding wrong object to model of calculate method inside MainController :
#RequestMapping(value = "/calculate",method = RequestMethod.GET)
public String calculate(Model model,Basket basket){
model.addAttribute("Basket",basket);
return "calculate";
}
So, I removed Basket argument from method and NullPointerException is solved :
#RequestMapping(value = "/calculate",method = RequestMethod.GET)
public String calculate(Model model){
model.addAttribute("Basket",basket);
return "calculate";
}

Spring security jdbc authentication using UserDetailsService with custom login form not working

People I need some help with this subject.. I am really new using Spring Security and I am trying to use a custom login form with database authentication, but I have not gotten positive results.
Currently my application is throwing this Exception when I hit the button login in me web page:
org.springframework.security.authentication.InternalAuthenticationServiceException
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:125)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at com.alcaldia.lineatransportealcaldiafalcon.service.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:28)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
Here are the correspondig code:
customUserDetailsService
#Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
#Autowired
private UserService userService;
#Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
throws UsernameNotFoundException {
//User user = userService.findBySso(ssoId);
User user = userService.findBySso(ssoId);
System.out.println("User : "+user);
if(user==null){
System.out.println("User not found");
throw new UsernameNotFoundException("Username not found");
}
return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(),
user.getState().equals("Active"), true, true, true, getGrantedAuthorities(user));
}
private List<GrantedAuthority> getGrantedAuthorities(User user){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(UserProfile userProfile : user.getUserProfiles()){
System.out.println("UserProfile : "+userProfile);
authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));
}
System.out.print("authorities :"+authorities);
return authorities;
}
}
UserService
public interface UserService {
User findById(int id);
User findBySso(String sso);
}
UserServiceImpl
#Service("userService")
public class UserServiceImpl implements UserService{
private static Log logger = LogFactory.getLog(UserServiceImpl.class);
#Autowired
private UserDao dao;
#Transactional
public User findById(int id) {
return dao.findById(id);
}
#Transactional
public User findBySso(String sso) {
System.err.println("ESTOY EN EL USERSERVICEIMPL");
logger.error("ESTOY EN EL USERSERVICEIMPL " + sso);
logger.error("****************************");
return dao.findBySSO(sso);
}
}
UserDao
public interface UserDao {
User findById(int id);
User findBySSO(String sso);
}
userDaoImpl
#Repository("userDao")
public class UserDaoImpl extends AbstractDao<Integer, User> implements UserDao {
private static Log logger = LogFactory.getLog(UserDaoImpl.class);
public User findById(int id) {
return getByKey(id);
}
public User findBySSO(String sso) {
System.err.println("ESTOY EN EL userdaoimpl");
logger.error("ESTOY EN EL userdaoimpl " + sso);
logger.error("****************************");
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("ssoId", sso));
return (User) crit.uniqueResult();
}
}
AbstractDao
public abstract class AbstractDao<PK extends Serializable, T> {
private final Class<T> persistentClass;
#SuppressWarnings("unchecked")
public AbstractDao(){
this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
#PersistenceContext
EntityManager em;
#SuppressWarnings("unchecked")
public T getByKey(PK key) {
return (T) em.find(persistentClass, key);
//return (T) getSession().get(persistentClass, key);
}
public void persist(T entity) {
em.persist(entity);
}
public void delete(T entity) {
em.remove(entity);
}
protected Criteria createEntityCriteria(){
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> criteria = cb.createQuery(persistentClass);
return (Criteria) criteria;
}
}
and my security conf
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http auto-config="true" >
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/home" access="permitAll" />
<intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
<intercept-url pattern="/dba**" access="hasRole('ADMIN') and hasRole('DBA')" />
<form-login login-page="/login"
username-parameter="ssoId"
password-parameter="password"
authentication-failure-url="/Access_Denied" />
<csrf/>
</http>
<authentication-manager >
<authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
<beans:bean id="customUserDetailsService" class="com.alcaldia.lineatransportealcaldiafalcon.service.CustomUserDetailsService" />
</beans:beans>
But I am getting NPE.. I've looked into another examples but somehow none of them have worked for me :/ This example It has been the only one that "worked" but it is not working completely yet.
Please, help me out with this, What I am missing?
EDIT: I am adding the servlet-context.xml
<mvc:annotation-driven/>
<context:component-scan base-package="com.alcaldia.lineatransportealcaldiafalcon.service" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="url" value="jdbc:jtds:sqlserver://localhost/:1433;DatabaseName=learning" />
<property name="username" value="sa" />
<property name="password" value="Osman1994*" />
</bean>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean> -->
<!-- Configure the entity manager factory bean -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.alcaldia.lineatransportealcaldiafalcon.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Configure the transaction manager bean -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Enable annotation driven transaction management -->
<tx:annotation-driven/>
<!-- Transaction Manager
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean> -->
<!-- Enable #Transactional annotation
<tx:annotation-driven/> -->

hibernate can't save data

when i use hibernate to save entity i found that session can't save it in Transaction. i must flush and clear session.but i have not to do like this before in other projects,is there anything wrong with the transaction configs in my xml files?Any answers are appreciated : )
hibernate.cfg.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"
xmlns:aop="http://www.springframework.org/schema/aop"
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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="classpath:application.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${db.userName}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<bean id="sessionFactory" name="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<!--<prop key="current_session_context_class">thread</prop>-->
</props>
</property>
<property name="packagesToScan" value="com.gtis"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--<bean id="transactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>-->
<!--<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="import*" propagation="REQUIRED" />
<tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* com.gtis.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>-->
</beans>
Dao
package com.gtis.dao;
import com.gtis.model.Student;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by u on 2016/3/15.
*/
#Repository
public class StudentDao {
#Resource
private SessionFactory sessionFactory;
private Session getSession(){
return sessionFactory.getCurrentSession();
}
public Student query(String id) throws Exception{
if(StringUtils.isBlank(id)){
return (Student)getSession().get(Student.class,id);
}else{
throw new Exception("id is required");
}
}
public List<Student> queryAll(){
String hql = "from com.gtis.model.Student";
Query query = getSession().createQuery(hql);
return query.list();
}
public void save(Student student)throws Exception{
if(student!=null){
System.out.println("sessionFactory="+sessionFactory);
System.out.println("session="+getSession());
// Session session = getSession();
getSession().save(student);
// session.flush();
// session.clear();
// session.close();
}else{
throw new Exception("object is required");
}
}
public void delete(Student student)throws Exception{
if(student!=null){
getSession().delete(student);
}else{
throw new Exception("object is required");
}
}
}
Service
package com.gtis.service;
import com.gtis.dao.StudentDao;
import com.gtis.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by u on 2016/3/15.
*/
#Service
public class StudentService {
#Autowired
StudentDao studentDao;
public Student getStudent(String id) throws Exception {
return studentDao.query(id);
}
public List<Student> getAll() throws Exception{
return studentDao.queryAll();
}
#Transactional
public void save(Student student)throws Exception{
studentDao.save(student);
}
#Transactional
public void delete(Student student) throws Exception{
studentDao.delete(student);
}
}
> Controller
package com.gtis.controller;
import com.gtis.model.Student;
import com.gtis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by u on 2016/3/15.
*/
#Controller
public class StudentController {
#Autowired
StudentService studentService;
#RequestMapping("get")
public String get(){
Student student = new Student();
student.setName("avc");
try {
studentService.save(student);
} catch (Exception e) {
e.printStackTrace();
}
return "somwhere";
}
}
Your DAO should implement an interface and inject that interface via Autowired to your Service which uses the #Transactional annotation in order to work.
So:
#Repository
public class StudentDao implements StudentDaoInterface {
//your rest code here
}
And:
#Service
public class StudentService {
#Autowired
StudentDaoInterface studentDao;
public Student getStudent(String id) throws Exception {
return studentDao.query(id);
}
public List<Student> getAll() throws Exception{
return studentDao.queryAll();
}
#Transactional
public void save(Student student)throws Exception{
studentDao.save(student);
}
#Transactional
public void delete(Student student) throws Exception{
studentDao.delete(student);
}
}
And of course dont forget to declare your public methods of your DAO to the interface.
Oh and do the same for your Service class (interface, autowire the interface instead of the class etc).
You should Autowired the sessionfactory to give spring a full control to commit your transactions.

Not able to use injected properties in spring beans

below is my spring-database.xml file. I can use sessionFactory in userDao. I also can use userDao in myUserDetailsService class. but when i try to use sessionFactory in registrationDao it gives me NullPointerException. same happens when i try to use registrationDao in registrationService service.
i am getting confused. please help.
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<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://localhost:3306/myds" />
<property name="username" value="root" />
<property name="password" value="mypass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.findsuvidha.web.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.findsuvidha.web.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myUserDetailsService" class="com.findsuvidha.web.service.MyUserDetailsService">
<property name="userDao" ref="userDao" />
</bean>
<bean id="registrationDao" class="com.findsuvidha.web.dao.RegistrationDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="registrationService" class="com.findsuvidha.web.service.RegistrationService">
<property name="registrationDao" ref="registrationDao" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.findsuvidha.web.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
</aop:config>
</beans>
Edit1:-Dao and DaoImpl which are able to use injected property
UserDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.entity.LoginMaster;
public interface UserDao {
LoginMaster findByUserName(String username);
}
UserDaoImpl.java
package com.findsuvidha.web.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import com.findsuvidha.web.entity.LoginMaster;
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public LoginMaster findByUserName(String email) {
List<LoginMaster> users = new ArrayList<LoginMaster>();
users = getSessionFactory().getCurrentSession().createQuery("from LoginMaster where email=?")
.setParameter(0, email).list();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Dao and DaoImpl which are not able to use injected property
RegistrationDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.transferobject.NewUser;
public interface RegistrationDao {
void insertUser(NewUser user);
}
RegistrationDaoImpl.java
package com.findsuvidha.web.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.findsuvidha.web.entity.LoginMaster;
import com.findsuvidha.web.entity.UserDetail;
import com.findsuvidha.web.transferobject.NewUser;
public class RegistrationDaoImpl implements RegistrationDao{
private SessionFactory sessionFactory;
private LoginMaster loginUser = new LoginMaster();
private UserDetail userDetail = new UserDetail();
#Override
public void insertUser(NewUser user) {
System.out.println("entered dao impl");
userDetail.setEmail(user.getEmail());
userDetail.setFirstName(user.getFirstName());
userDetail.setLastName(user.getLastName());
userDetail.setMobileNo(user.getMobileNumber());
loginUser.setEmail(user.getEmail());
loginUser.setPassword(user.getPassword());
loginUser.setRoleFlag("ROLE_USR");
loginUser.setUserDetail(userDetail);
System.out.println("before session save");
getSessionFactory().getCurrentSession().save(loginUser);
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}

Getting java.lang.NullPointerException while getSession().save(entity);

I want to add object data and want to save in DB table, everything working fine but it gives me an error :
java.lang.NullPointerException
on line getSession().save(entity);
I have called this method in code :
#Service
public class AddCategoryProcessor implements ICommandProcessor<AddCategory> {
#Autowired
private IPatronCategoryRepository patronCategoryRepository = new PatronCategoryRepository();
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
patronCategoryRepository.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
}
following is my xml file :
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/abc"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ngl.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Here is a getSession() method :
#Override
public Session getSession() {
return getSessionFactory().getCurrentSession();
}
Here is a sessionFactory declaration :
protected SessionFactory sessionFactory;
Any guesses why it's NULLPOINTEREXCEPTION ??
UPDATE :
java.lang.NullPointerException
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:32)
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:16)
at com.ngl.controllerapis.BaseApiController.ProcessRequest(BaseApiController.java:29)
at com.ngl.controllerapis.PatronCategoryController.addCategory(PatronCategoryController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
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:744)
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and xml for transaction manager
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
in repository
#Autowired
protected SessionFactory sessionFactory;
Your config is a bit incomplete. You should delegate session management completely to Spring
Add in you spring xml file:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Then, in your PatronCategoryRepository class, extend HibernateDaoSupport and add this constructor:
public class PatronCategoryRepository extends HibernateDaoSupport implements IPatronCategoryRepository{
#Autowired
public PatronCategoryRepository(HibernateTemplate hibernateTemplate) {
super();
super.setHibernateTemplate(hibernateTemplate);
}
[...]
}
In AddCategoryProcessor, leave the definition of the repository like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
And finally your method:
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
getHibernateTemplate.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
In case you still need to access directy the SessionFactory, the only thing you have to do is inject it into PatronCategoryRepository:
#Repository
public class PatronCategoryRepository implements IPatronCategoryRepository{
#Autowired
protected SessionFactory sessionFactory;
public PatronCategoryRepository() {
}
public PatronCategory save(PatronCategory entity){
return getSession().save(entity);
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
And remember to remove the new clause from AddCategoryProcessor, leaving it like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
Employee.java
package com.javacodegeeks.snippets.enterprise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Employee1")
public class Employee implements Serializable {
#Id
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private int age;
public Employee() {
}
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 long getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
EmployeeDao.java
package com.javacodegeeks.snippets.enterprise.dao;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public interface EmployeeDAO {
public void saveEmployee(Employee employee);
Employee findEmployeeById(int id);
void updateEmployee(Employee employee);
void deleteEmployee(Employee employee);
}
EmployeeDaoImpl.java
package com.javacodegeeks.snippets.enterprise.dao;
import java.io.Serializable;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public class EmployeeDAOImpl implements EmployeeDAO {
private HibernateTemplate template;
private SessionFactory sessionFactory;
#Autowired
public void setTemplate(HibernateTemplate template) {
this.template = template;
// template.setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
new HibernateTemplate(sessionFactory);
}
/*
* public void saveEmployee(Employee employee) {
* sessionFactory.getCurrentSession().save(employee);
*
* }
*/
public Employee findEmployeeById(int id) {
return (Employee) sessionFactory.getCurrentSession().get(
Employee.class, id);
}
public void updateEmployee(Employee employee) {
sessionFactory.getCurrentSession().update(employee);
}
public void deleteEmployee(Employee employee) {
sessionFactory.getCurrentSession().delete(employee);
}
public void saveEmployee(Employee employee) {
sessionFactory.getCurrentSession().persist(employee);
template.saveOrUpdate(employee);
}
}
Application COntext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />
<!-- <tx:annotation-driven/> -->
<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://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.javacodegeeks.snippets.enterprise.model.Employee</value>
</list>
</property>
<!-- <property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property> -->
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> -->
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="d" class="com.javacodegeeks.snippets.enterprise.dao.EmployeeDAOImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
pleas ehelp me :-)

Categories