spring 3 autowire - spring-mvc

I'm using spring3 and hibernate 3 to build my application, I can't autowire the session factory
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.gepmag.model.Message;
#Repository("iMessageTicketDao")
public class MessageTicketDaoImpl implements IMessageTicketDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void saveMessage(Message message) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().save(message);
}
#Override
public List<Message> listTicketMessages(Long IdTicket) {
// TODO Auto-generated method stub
List<Message> list = sessionFactory.getCurrentSession()
.createQuery("from Message where IdTicket=?")
.setParameter(0, IdTicket).list();
return list;
}
#Override
public void deleteMessage(Message message) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().delete(message);
}
#Override
public void updateMessage(Message message) {
// TODO Auto-generated method stub
sessionFactory.getCurrentSession().update(message);
}
#Override
public Message getMessageById(int idMessage) {
// TODO Auto-generated method stub
List<Message> list = sessionFactory.getCurrentSession()
.createQuery("from Message where where IdMessage=?")
.setParameter(0, idMessage).list();
return (Message) list.get(0);
}
#Override
public List<Message> listAllMessages() {
// TODO Auto-generated method stub
List<Message> list = sessionFactory.getCurrentSession()
.createQuery("from Message").list();
return list;
}
}
And context xml configuration:
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">
<context:annotation-config/>
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.gepmag" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<!-- <context:annotation-driven/> -->
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.gepmag.model"/>
<property name="annotatedClasses">
<list>
<value>com.model.Client</value>
<value>com.model.Erreurs</value>
<value>com.model.Message</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="messageSource"
class="com.service.MessageBundle">
<property name="basename" value="com.service.MessageBundle" />
</bean>
</beans>
I always have this exception
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/PortailSupport] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.gepmag.dao.MessageTicketDaoImpl.saveMessage(MessageTicketDaoImpl.java:49)
at com.gepmag.service.TicketMessageServiceImpl.saveMessage(TicketMessageServiceImpl.java:48)
this is the service
package com.gepmag.service;
#Service("iTicketMessageService")
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class TicketMessageServiceImpl implements ITicketMessageService {
#Autowired(required=true)
private IMessageTicketDao iMessageTicketDao;
#Override
public void saveMessage(Message message) {
// TODO Auto-generated method stub
iMessageTicketDao.saveMessage(message);
}
#Override
public List<Message> listTicketMessages(Long IdTicket) {
// TODO Auto-generated method stub
List<Message> list = iMessageTicketDao.listTicketMessages(IdTicket);
return list;
}
#Override
public void deleteMessage(Message message) {
// TODO Auto-generated method stub
iMessageTicketDao.deleteMessage(message);
}
#Override
public void updateMessage(Message message) {
// TODO Auto-generated method stub
iMessageTicketDao.updateMessage(message);
}
#Override
public Message getMessageById(int idMessage) {
// TODO Auto-generated method stub
Message message = iMessageTicketDao.getMessageById(idMessage);
return message;
}
#Override
public List<Message> listAllMessages() {
// TODO Auto-generated method stub
List<Message> list = iMessageTicketDao.listAllMessages();
return list;
}
}
my controller
#Controller
#RequestMapping("/forms/ticket")
public class TicketController {
#Autowired
private TicketMessageServiceImpl iTicketMessageService ;
#RequestMapping(value="/addticket", method = RequestMethod.GET)
public String addTicket(Map model) {
TicketForm ticket = new TicketForm();
List<CategorieTicket> categorieList = LoadCategorieList();
List<SeveriteTicket> severiteList = LoadSeveriteList();
List<PrioriteTicket> prioriteList = LoadPrioriteList();
List<ProblemeTicket> problemeList = LoadProblemeList();
List<EtatSysteme> etatSystemeList = LoadEtatSysteme();
List<ContexteProblemeTicket> contexteList = LoadContexteProblemeTicket();
List<EtatInstance> etatInstanceList = LoadEtatInstance();
model.put("ticket", ticket);
model.put("categorieList", categorieList);
model.put("severiteList", severiteList);
model.put("prioriteList", prioriteList);
model.put("problemeList", problemeList);
model.put("etatSystemeList", etatSystemeList);
model.put("contexteList", contexteList);
model.put("etatInstanceList", etatInstanceList);
return "newticket";
}
public List<CategorieTicket> LoadCategorieList(){
List <CategorieTicket>categorieList = new ArrayList<CategorieTicket>();
categorieList.add(new CategorieTicket(1,"Nouveau Besoin","description du nouveau besoin"));
categorieList.add(new CategorieTicket(2,"Anomalie","description de l'anomalie"));
categorieList.add(new CategorieTicket(3,"incident de production","description de l'incident de la production"));
categorieList.add(new CategorieTicket(4,"crise de production","description du crise de la production"));
return categorieList;
}
public List<SeveriteTicket> LoadSeveriteList(){
List<SeveriteTicket> severiteList = new ArrayList<SeveriteTicket>();
severiteList.add(new SeveriteTicket(1,"Bloquant","description de la sévérité bloquante"));
severiteList.add(new SeveriteTicket(2,"Critique","description de la sévérité critique"));
severiteList.add(new SeveriteTicket(3,"Majeur","description de la sévérité majeure"));
severiteList.add(new SeveriteTicket(4,"Mineur","description de la sévérité mineur"));
return severiteList;
}
public List<PrioriteTicket> LoadPrioriteList(){
List<PrioriteTicket> PrioriteList = new ArrayList<PrioriteTicket>();
PrioriteList.add(new PrioriteTicket(1,"Faible","priorité faible"));
PrioriteList.add(new PrioriteTicket(2,"Moyenne","priorité moyenne"));
PrioriteList.add(new PrioriteTicket(3,"Haute","priorité forte"));
return PrioriteList;
}
public List<ProblemeTicket> LoadProblemeList(){
List<ProblemeTicket> ProblemeList = new ArrayList<ProblemeTicket>();
ProblemeList.add(new ProblemeTicket(1,"Dysfonctionnement c2o","probleme de fonctionnement c2o") );
ProblemeList.add(new ProblemeTicket(2,"Problème d'installation","probleme d'installation") );
ProblemeList.add(new ProblemeTicket(3,"Modification licence","probleme de modification de la licence"));
return ProblemeList;
}
public List<EtatSysteme> LoadEtatSysteme(){
List<EtatSysteme> StateSystemList = new ArrayList<EtatSysteme>();
StateSystemList.add(new EtatSysteme(1,"Complètement bloqué","Systeme complètement bloqué"));
StateSystemList.add(new EtatSysteme(2,"Fortement perturbé","Systeme fortement perturbé"));
StateSystemList.add(new EtatSysteme(3,"Perturbation résiduelle","Systeme qui est Perturbé résiduellement"));
return StateSystemList;
}
public List<ContexteProblemeTicket> LoadContexteProblemeTicket(){
List<ContexteProblemeTicket> ContexteList = new ArrayList<ContexteProblemeTicket>();
ContexteList.add(new ContexteProblemeTicket(1,"Lors de l'installation",""));
ContexteList.add(new ContexteProblemeTicket(2,"En cours de l'exécution",""));
return ContexteList;
}
public List<EtatInstance> LoadEtatInstance(){
List<EtatInstance> EtatInstanceList = new ArrayList<EtatInstance>();
EtatInstanceList.add(new EtatInstance(1,"Aborté"," instance aborté"));
EtatInstanceList.add(new EtatInstance(2,"En attente","instance en attente"));
return EtatInstanceList;
}
#RequestMapping("/ticketvalide.html")
public String processTicketForm(Map model,#Valid #ModelAttribute("ticket") TicketForm ticket){
Message message = new Message();
message.setObjet(ticket.getSujetTicket());
message.setTextMessage(ticket.getMessageTicket());
message.setPath(ticket.getFile());
iTicketMessageService.saveMessage(message);
return "detailsticket";
}
}

Related

How to catch Spring bean creation error?

AdminService.java
package service;
import java.awt.Window.Type;
import java.util.HashMap;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import dao.IMemberDAO;
import model.Member;
#Service
public class MemberService
{
#Autowired
private IMemberDAO memberDao;
// 로그인
public HashMap<String, Object> login(String id,String pw)
{
HashMap<String, Object> result = memberDao.selectOne(id);
if(result != null) // 존재하는 값이 있으면
{
String opwd = (String) result.get("pw"); // opwd = 존재하는값의 pw값을 가져온 값
if(opwd.equals(pw))
{
return result; // true면 존재하는값을 반환
}
else
{
return null;
//return null; // 아니면 값을 반환하지 않음.
}
}
else // 존재하는 값이 없다면
{
return null;
}
}
// 아이디 체크
public boolean idCheck(String loginPerson)
{
HashMap<String, Object> user = memberDao.selectOne(loginPerson);
if(user != null)
{
return false;
}
else
{
return true;
}
}
// 멤버 추가
public boolean insertMember(Member member)
{
if(idCheck(member.getId()))
{
memberDao.insertMember(member);
return true;
}
else
{
return false;
}
}
public HashMap<String, Object> getMemberInfo(String id)
{
return memberDao.selectOne(id);
}
// 회원 수정
public void memberUpdate(HashMap<String, Object> params)
{
System.out.println("params is : " + params);
memberDao.updateMember(params);
}
// 회원삭제
public boolean memberDelete(String id,String pw)
{
HashMap<String, Object> user = memberDao.selectOne(id);
String pw2 = (String) user.get("pw");
System.out.println("id and pw is : " + id + "/" + pw);
System.out.println("pw2 is : " + pw2);
if(pw2.equals(pw))
{
memberDao.deleteMember(id);
System.out.println("return true");
return true;
}
else
{
System.out.println("return false");
return false;
}
}
}
AdminController.java
package controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.AdminService;
import service.MemberService;
#Controller
public class AdminController
{
#Autowired
public AdminService aService;
// 관리자 로그인 폼 페이지
#RequestMapping("admin.do")
public String adminLoginPage()
{
return "adminLoginPage";
}
// 관리자 로그인했을 시 요청
#RequestMapping("adminLoginOK.do")
#ResponseBody
public String adminMainPage(#RequestParam(required=false) String id, #RequestParam(required=false)String pw,HttpSession session,HttpServletRequest req,HttpServletResponse resp)
{
HashMap<String, Object> adminLoginIdentify = aService.adminLogin(id, pw);
//if(session.getAttribute("id") == null){System.out.println("zzz kkk");}
//String admin_id = (String) session.getAttribute("id");
if(adminLoginIdentify != null)
{
return "1";
}
else
{
return "0";
}
}
#RequestMapping("adminPage.do")
public String adminPage(
#RequestParam(required = false) String keyword,
#RequestParam(defaultValue="0") int type,
HttpSession session,HttpServletRequest resquest,HttpServletResponse response) throws IOException
{
ModelAndView mav = new ModelAndView();
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("type", type);
params.put("keyword", keyword);
System.out.println(params);
return "adminMainPage";
}
}
adminDaoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.IAdminDAO">
<select id="selectOne" parameterType="Strig" resultType="java.util.HashMap">
select * from member where id = #{id}
</select>
<select id="selectMemberAll" resultType="java.util.HashMap">
select * from member
</select>
</mapper>
AdminDao.java
package dao;
import java.util.HashMap;
public interface IAdminDAO
{
public HashMap<String, Object> selectOne(String id);
}
The code before modifying the applicationContext file is shown below.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath*:dao/mapper/*.xml"></property>
</bean>
<bean id="memberDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="dao.IMemberDAO"></property>
</bean>
</beans>
This is the appliCation code after the modification.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:dao/mapper/*.xml"></property>
<property name="typeAliasesPackage" value="model"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
The project worked well before the applicationContext file was modified,
but after the code has been modified, an error occurs.
error code is that.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.IAdminDAO service.AdminService.adminDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.IAdminDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
I thought about the cause of the error,
but I think it is because I did not insert the service annotation.
However, there is no typos in any way, and everything is written correctly and errors occur. Is there something I don't know?
Can you tell me what caused this error?
And what about the solution?
Please help me..
Try to change this code of yours:
#Autowired
public AdminService aService;
to this:
#Autowired
public AdminService adminService;
because when you Autowire, he can't see aService on your context that's why he can't create instance of adminService as a default name of your Service bean.
EDIT:
Another thing is you have to implement your interfaces to a concrete class in order to instantiate beans, you can't instantiate interfaces remember, so you need concrete beans to implement what is on your interfaces. Like this:
#Repository
public class IAdminDAOImpl implements IAdminDAO {
//Implementation here
}
#Service
public class AdminServiceImpl implements AdminService {
//Implementation here
}

No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
when I do a test with JUnit, persist method works and I see that my object is inserted, but when I call the method via my Controller doesn't work
here is my Project :
applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.xsd
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-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!-- <bean id="notification" class="com.app.sqli.notification.NotificationTask" /> -->
<!-- <task:scheduled-tasks> -->
<!-- <task:scheduled ref="notification" method="notifier" cron="*/2 * * * * *"/> -->
<!-- </task:scheduled-tasks> -->
<context:component-scan base-package="com.app.sqli" />
<mvc:annotation-driven />
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.app.sqli.entities" />
<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 id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/sqli" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<tx:annotation-driven />
</beans>
my Model Class:
package com.app.sqli.models;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Collaborateur {
#Id
private int id;
private String nom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
my DAO Class
package com.app.sqli.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import com.app.sqli.models.Collaborateur;
#Repository
public class CollaborateurDao implements IcollaborateurDao{
#PersistenceContext
private EntityManager em;
#Override
public void addCollaborateur(Collaborateur c) {
em.persist(c);
}
}
My Service Class
package com.app.sqli.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.app.sqli.dao.IcollaborateurDao;
import com.app.sqli.models.Collaborateur;
#Service
#Transactional
public class CollaborateurService implements IcollaborateurService{
#Autowired
private IcollaborateurDao cdao;
#Override
public void addCollaborateur(Collaborateur c) {
cdao.addCollaborateur(c);
}
}
And My Controller
package com.app.sqli.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.app.sqli.models.Collaborateur;
import com.app.sqli.services.IcollaborateurService;
#org.springframework.stereotype.Controller
public class Controller {
#Autowired
private IcollaborateurService cserv;
#RequestMapping(value = "/index")
public String index(Model m) {
System.out.println("insertion ...");
Collaborateur c = new Collaborateur();
c.setId(11);
c.setNom("nom");
cserv.addCollaborateur(c);
return "index";
}
}
thank you #mechkov for your time and help,
My problem is resolved by changing my configuration file, so I have used a Configuration Class with annotations and its works so fine, I still Don't know where the problem was
#Configuration
#ComponentScan(basePackages = "your package")
#EnableTransactionManagement
public class DatabaseConfig {
protected static final String PROPERTY_NAME_DATABASE_DRIVER = "com.mysql.jdbc.Driver";
protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "password";
protected static final String PROPERTY_NAME_DATABASE_URL = "jdbc:mysql://localhost:3306/databasename";
protected static final String PROPERTY_NAME_DATABASE_USERNAME = "login";
private static final String PROPERTY_PACKAGES_TO_SCAN = "where your models are";
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter){
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
return entityManagerFactoryBean;
}
#Bean
public BasicDataSource dataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(PROPERTY_NAME_DATABASE_DRIVER);
ds.setUrl(PROPERTY_NAME_DATABASE_URL);
ds.setUsername(PROPERTY_NAME_DATABASE_USERNAME);
ds.setPassword(PROPERTY_NAME_DATABASE_PASSWORD);
ds.setInitialSize(5);
return ds;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter(){
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.MYSQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
//I'm using MySQL5InnoDBDialect to make my tables support foreign keys
adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
return adapter;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
I do not know if anyone who is reading this (today) has the same case as mine, but I had the same problem. Luckly, I could fix it by simply putting the following in my spring-conf.xml:
<beans xmlns="http://www.springframework.org/schema/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.xsd">
<bean id="tManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<!-- This does the trick! -->
<tx:annotation-driven transaction-manager="tManager" />
Note: I'm using declarative transactions through annotations. So, if you do, annotating your method with #Transactional can also solve your problem.
REFERENCE:
http://blog.jhades.org/how-does-spring-transactional-really-work/
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/transaction.html
Just to confirm, that adding last bean definition solves this issue !
My config class is as below :
#Configuration
#EnableTransactionManagement
#ComponentScan
public class OFSConfig {
#Bean
public IDAO<FuelStation> getFSService() {
return new FSService();
}
#Bean
public LocalEntityManagerFactoryBean emfBean() {
LocalEntityManagerFactoryBean e = new LocalEntityManagerFactoryBean();
e.setPersistenceUnitName("org.superbapps.db_OWSDB_PU");
return e;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory em) {
return new JpaTransactionManager(em);
}
}
The service itself is as follows :
#Transactional
#Repository
public class FSService implements IDAO<FuelStation> {
#PersistenceContext
private EntityManager EM;
public EntityManager getEM() {
return EM;
}
public void setEM(EntityManager EM) {
this.EM = EM;
}
#Override
public List<FuelStation> getAll() {
return EM.createNamedQuery("FuelStation.findAll")
.getResultList();
}
#Override
public FuelStation getByID(String ID) {
FuelStation fs = (FuelStation) EM.createNamedQuery("FuelStation.findById")
.setParameter("id", ID)
.getSingleResult();
return fs;
}
#Override
public void update(FuelStation entity) {
EM.merge(entity);
}
}

Getting "no transaction is in progress" when calling em.flush();

Hi i am trying to integrate jpa with spring mvc and getting "no transaction is in progress" when trying to call flush() method.
I can make out that something is wrong with transactions even though i have used #Transactional the method is not running in a transaction.
Spring.xml
`<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:annotation-config />
<context:component-scan base-package="com.sushant.mvc" />
<bean class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1/mvc" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="1800000" />
<property name="numTestsPerEvictionRun" value="3" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
<property name="validationQuery" value="SELECT 1" />
<property name="maxActive" value="-1" />
<property name="maxIdle" value="-1" />
<!-- This property should be set to a value so as to support minimum 500
BC concurrent connections. For test, set this value to 5 -->
<property name="initialSize" value="5" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="proxy" transaction-manager="transactionManager"/>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<!-- <property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property> -->
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="defaultPersistenceUnitName" value="persistenceUnit" />
</bean>
<!-- <bean id="user" class="com.sushant.mvc.entities.User"/> -->
</beans>
`
User.java
'
package com.sushant.mvc.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
#Entity
#Component
#Configurable
public class User {
#PersistenceContext(name = "persistenceUnit")
transient public EntityManager em;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private String userName;
#Column
private String email;
#Column
private String firstName;
#Column
private String lastName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static final EntityManager entityManager() {
EntityManager em = new User().em;
if (em == null)
throw new IllegalStateException(
"Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
#Transactional
public void save(User user) {
em.persist(user);
em.flush();
}
}
'
HomeController.java
'
package com.sushant.mvc;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.sushant.mvc.entities.User;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Autowired
User user;
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
#Transactional
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! the client locale is " + locale.toString());
//user.em.getTransaction().begin();
// User user=new User();
user.setEmail("sushantmahajan05#gmail.com");
user.setFirstName("Sushant");
user.setLastName("Mahajan");
user.setUserName("sushantmahajan05");
user.save(user);
User u=user.em.find(User.class, new Integer(1).longValue());
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home/home";
}
}
'
servlet-context.xml
'
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.sushant.mvc" />
</beans:beans>
'
You may try creating a persistence.xml file .
You can take a look at te following example : JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()

Bootstrap with Spring MVC

I am trying to use bootstrap to style my app but I won't apply the styles. This is what is in my JSP
<c:url value="css/bootstrap.min.css" var="cssBoostrap" />
<link href="${cssBootstrap}" rel="stylesheet">
This css folder is on the same level as WEB-INF not inside of it but it won't work if it is inside of it or even if the files are inside of the view dir. What could the problem possibly be? I no longer get the no mapping error when adding the mapping to my servlet.xml but yet it still doesn't see the file or I can assume it doesn't because no styling is applied, then I change it to link to the online hosted version and all my styles are applied correctly.
Servlet 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:mvc="http://www.springframework.org/schema/mvc" 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-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.eaglecrk.recognition" />
<mvc:annotation-driven />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/system.properties</value>
</list>
</property>
</bean>
<!-- messageSource -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>file:${external.property.directory}PMS.EOTM.SendEmail</value>
</list>
</property>
</bean>
<!-- dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
</props>
</property>
<property name="packagesToScan" value="com.eaglecrk.recognition.persistence" />
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value = "${email.host}" />
<property name="port" value="${email.port}" />
<property name="username" value="${email.username}" />
<property name="password" value="${email.password}" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.ssl.trust">${email.mail.smtp.ssl.trust}</prop>
<prop key="mail.smtp.starttls.enable">${email.mail.smtp.starttls.enable}</prop>
<prop key="mail.smtp.auth">${email.mail.smtp.auth}</prop>
</props>
</property>
</bean>
</beans>
Controller
package com.eaglecrk.recognition.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.eaglecrk.recognition.dao.award.AwardDao;
import com.eaglecrk.recognition.dao.award.AwardDaoInterface;
import com.eaglecrk.recognition.dao.employee.EmployeeDaoInterface;
import com.eaglecrk.recognition.model.AwardTypeModel;
import com.eaglecrk.recognition.model.EmployeeModel;
import com.eaglecrk.recognition.persistence.AwardNomination;
import com.eaglecrk.recognition.persistence.AwardType;
import com.eaglecrk.recognition.persistence.Employee;
import com.eaglecrk.recognition.util.Functions;
import com.eaglecrk.recognition.util.SpringMailSender;
#Controller
public class TestController extends BaseController implements MessageSourceAware {
private static final Logger LOG = LogManager
.getLogger(TestController.class);
#Autowired
private EmployeeDaoInterface employeeDao;
#Autowired
private AwardDaoInterface awardDao;
#Autowired
private SpringMailSender springMailSender;
/**
* #param request
* #return (ModelAndView) object
*/
#RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView test() {
try {
LOG.info("Entered the controller");
springMailSender.sendMail();
} catch (Exception e) {
e.printStackTrace();
}
ModelAndView mav = new ModelAndView();
ArrayList<String> names = new ArrayList<String>();
List<Employee> employees = employeeDao.findAll();
Collections.sort(employees, Functions.lastNameOrder);
for (Employee employee : employees) {
EmployeeModel model = new EmployeeModel(employee);
names.add(model.getLocation().getLocationId() + " " +
model.getFirstName() + " " + model.getLastName());
}
mav.addObject("names", names);
mav.setViewName("test");
return mav;
}
#RequestMapping(value = "/test", method = RequestMethod.POST)
public void addNomination(
#ModelAttribute("SpringWeb") AwardNomination nomination,
ModelMap model) {
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
ModelAndView mav = new ModelAndView();
mav.setViewName("login");
return mav;
}
#RequestMapping(value="/newAwardType", method=RequestMethod.GET)
public ModelAndView addAward() {
ModelAndView mav = new ModelAndView();
ArrayList<AwardTypeModel> models = new ArrayList<AwardTypeModel>();
try{
AwardTypeModel newAwardTypeModel = new AwardTypeModel();
newAwardTypeModel.setActive(false);
newAwardTypeModel.setName("AwardTypeModel.name");
newAwardTypeModel.setDescription("AwardTypeModel.description");
// newAwardTypeModel.setId(123456);
newAwardTypeModel.setCreated(new Date());
newAwardTypeModel.setModified(new Date());
models.add(newAwardTypeModel);
} catch (Exception e){
e.printStackTrace();
}
mav.addObject("awardTypes", models);
mav.addObject("model", new AwardTypeModel());
mav.setViewName("addAward");
return mav;
}
#RequestMapping(value="/addAward", method=RequestMethod.POST)
public String addAwardForm(#ModelAttribute("model") AwardTypeModel model, BindingResult result){
model.setCreated(new Date());
model.setModified(new Date());
AwardType dbo = (AwardType) model.convertToDb();
awardDao.save(dbo);
return "redirect:/test";
}
#Override
public void setMessageSource(MessageSource messageSource) {
// TODO Auto-generated method stub
}
}
Create one folder by name resources at same level as WEB-INF as shown below:
WebApp-|
| - resources -|
| |-styles-|
| | |-bootstrap.min.css
| |
| |-javascript-|
| |-example.js
|
| - WEB-INF
Include the following line in your servlet xml:
<mvc:resources mapping="/resources/**" location="/resources/"/>
Access these resources in your jsp as:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<link href="<c:url value="/resources/styles/bootstrap.min.css" />" rel="stylesheet">
<script src="<c:url value="/resources/javascript/example.js" />"></script>
....
You should declare in your dispatcher servlet config the location of you resources (e.g js, css, img etc.) :
<mvc:resources mapping="/public/**" location="/public/" />
location contains the path to your resources folder. mapping is how you call your resources in your jsp.
Don't forget to declare your mvc namespace in dispatcher config.
Following Prasads Answer above if you need Java based configuration for the same use -
#Configuration
#ComponentScan("com.eaglecrk.recognition")
#EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Also if you are using xml based configuration don't forget <mvc:default-servlet-handler/>

Spring 3, Hibernate 4 AutoWired sessionFactory with Generic DAO

Using Spring MVC 3 & Hibernate 4 I'm getting:
java.lang.NullPointerException
com.daniel.rr.dao.common.DAOImpl.getSession(DAOImpl.java:22)
com.daniel.rr.dao.common.DAOImpl.save(DAOImpl.java:27)
com.daniel.rr.controller.HelloController.printWelcome(HelloController.java:30)
This is the relevant spring configuration:
<context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan">
<list>
<value>com.daniel.rr.model</value>
<value>com.daniel.rr.dao</value>
<value>com.daniel.rr.dao.common</value>
<value>com.daniel.rr.controller</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/rr" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Generic DAO:
public interface DAO<T> {
T save(T t);
void delete(T t);
}
#Transactional
public abstract class DAOImpl<T> implements DAO<T> {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return sessionFactory.getCurrentSession();
}
#Override
public T save(T t) {
getSession().persist(t);
return t;
}
#Override
public void delete(T t) {
getSession().delete(t);
}
}
AccountDAO:
public class AccountDAO extends DAOImpl<Account> implements DAO<Account> {
}
MVC Controller:
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
//System.out.println("is null? " + sessionFactory);
AccountDAO dao = new AccountDAO();
Account account = new Account();
account.setUsername("hello");
account.setPassword("test");
dao.save(account);
model.addAttribute("message", "Hello world!");
return "hello";
}
}
I've searched thru StackOverflow and Google but I cannot find anything that helps.
I've tried using a Transaction on DAOImpl.save(T t) but it still has the same issue.
public T save(T t) {
Transaction tr = getSession().getTransaction();
tr.begin();
getSession().persist(t);
tr.commit();
return t;
}
Annotations are not inherited.
Add the transactional annotation to the concrete dao, not the abstract class.
You might like this too

Resources