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

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);
}
}

Related

Spring annotations #NotNull and #Size do not work

I've created a simple page project, which checks a single inputdata field "name" and if it's empty or size is less than 5, it has to show a error-message.
At the moment BindingResult thinks there is no error all the time.
Spring.xml file:
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="com.mvc" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Student class:
package com.mvc;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
#NotNull(message = "IsRequired!")
#Size(min = 5, message = "must be greater than 5!")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Controller:
package com.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
#Controller
public class StudentController {
#RequestMapping("/")
public String showPage(Model model){
model.addAttribute("student", new Student());
return "index";
}
#RequestMapping("/processForm")
public String processForm(
#Valid #ModelAttribute("student") Student student,
BindingResult theBindingResult) {
if (theBindingResult.hasErrors()) {
return "index";
} else {
return "student-confirm";
}
}
}
If required, i can post web.xml, and jsp pages.
Removed previous version of Tomcat(7.0) and installed latest version.

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
}

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()

spring 3 autowire

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";
}
}

GAE + JPA :java.lang.NoClassDefFoundError: Could not initialize class EMF

When i tried to connect my Cloud SQL via JPA the following error is generated :
2012-10-25 10:07:38.439
Error for /jpatest
java.lang.NoClassDefFoundError: Could not initialize class com.my.jpa.EMF
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:14)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
2012-10-25 10:07:38.440
Uncaught exception from servlet
java.lang.NoClassDefFoundError: Could not initialize class com.my.jpa.EMF
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:14)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
My EMF Class is
public final class EMF {
private static final EntityManagerFactory emfInstance = Persistence
.createEntityManagerFactory("JPATest");
private EMF() {
}
public static EntityManagerFactory get() {
return emfInstance;
}
}
EMF initialising portion is
public class ContactService {
private static Logger logger = Logger.getLogger(ContactService.class
.getName());
public void createContact(Contact c) {
logger.info("Entering createContact: [" + c.getFirstName() + ","
+ c.getLastName() + "]");
EntityManager mgr = EMF.get().createEntityManager();
try {
mgr.getTransaction().begin();
mgr.persist(c);
mgr.getTransaction().commit();
} finally {
mgr.close();
}
logger.info("Exiting createContact");
}
}
My Servlet is :
public class JPATestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
ContactService service = new ContactService();
service.createContact(new Contact("Manu", "Mohan", "686019", "TVM"));
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
web.xml is
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>JPATest</servlet-name>
<servlet-class>com.my.jpa.JPATestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JPATest</servlet-name>
<url-pattern>/jpatest</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPATest">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.my.jpa.Contact</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.google.cloud.sql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms://instance-name/stock" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>
</persistence-unit>
</persistence
Do you need to use final for EntityManagerFactory in EMF. Try to use Singleton Design Pattern for EMF. EntityManagerFactory class is thread-safe.
EMF.java
public final class EMF {
private EntityManagerFactory emfInstance;
private static EMF emf;
private EMF() {
}
public EntityManagerFactory get() {
if(emfInstance == null) {
emfInstance = Persistence.createEntityManagerFactory("JPATest");
}
return emfInstance;
}
public static EMF getInstance() {
if(emf == null) {
emf = new EMF();
}
return emf;
}
}
// usages
EntityManagerFactory emf = Emf.getInstance().get();
Here better way to use EntityManagerFactory in web applicaiton.

Resources