Issue Binding a List of Objects and there properties with Spring WebFlow 2 - spring-mvc

Im having great difficult binding the value of a checkbox to an object thats nested inside a List during a post back. Is there an issue with webflow and nested objects inside a list?.
jsp
<div style="margin-left: 15px; margin-bottom: 8px;">
<form:checkbox id="firmUserBeingEditedPermissionList[${status.index}].cascading" path="firmUserBeingEditedPermissionList[${status.index}].cascading"
onclick="toggleCascading(${status.index}, this, event);"/><spring:message code="setFirmPermissions.cascading" />
</div>
flow.xml
<input name="userName" required="true"/>
<on-start>
<evaluate expression="firmUserPermissionDetailViewBuilder.createFirmUserPermissionDetailView(userName)" result="flowScope.firmUserPermissionView" />
</on-start>
<view-state id="setFirmPermissions" view="admin/setFirmPermissions3" model="firmUserPermissionView">
<binder>
<binding property="firmUserBeingEditedPermissionList" required="true"/>
</binder>
<transition on="submitAddFirm" to="setFirms">
</transition>
<transition on="submitPermissions" to="viewAndConfirm"/>
<transition on="cancelSetFirmPermissions" to="cancelChange"/>
</view-state>
firmUserPermissionView
public class FirmUserPermissionView implements Serializable {
private static final long serialVersionUID = -7219027256643534729L;
public static final String KEY = "firmUserPermissionView";
private AbstractUser currentAdminUser;
private AbstractUser firmUser;
private List<UserPermissionFirmDetail> firmUsersCurrentUserPermissionDetailList;
private List<UserPermissionFirmDetailFBO> firmUserBeingEditedPermissionList;
private Map<String, Collection<FirmSession>> firmCdAndExchangeSessionMap;
private Map<String, Collection<Firm>> firmCdAndExchangeSubFirmMap;
private Map<String, Collection<String>> firmCdAndExchangeExcludedSubFirmMap;
private Collection<String> exchangeSymbolsAvailableToLoggedInUser;
private List<PresentableFirmPermission> unSelectedFirmPresentablePermissions;
private List<PresentableFirmPermission> selectedFirmPresentablePermissions;
public List<UserPermissionFirmDetail> getFirmUsersCurrentUserPermissionDetailList() {
return firmUsersCurrentUserPermissionDetailList;
}
public void setFirmUsersCurrentUserPermissionDetailList(
List<UserPermissionFirmDetail> firmUsersCurrentUserPermissionDetailList) {
this.firmUsersCurrentUserPermissionDetailList = firmUsersCurrentUserPermissionDetailList;
}
servlet
<bean id="flowController" class="org.springframework.webflow.mvc.servlet.FlowController">
<property name="flowExecutor" ref="flowExecutor"/>
</bean>
<flow:flow-executor id="flowExecutor" flow-registry="flowRegistry"/>
<!-- This creates an XmlFlowRegistryFactory bean -->
<flow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices">
<flow:flow-location path="/WEB-INF/flows/setFirmPermissions.xml"/>
</flow:flow-registry>
<flow:flow-builder-services id="flowBuilderServices" view-factory-creator="viewFactoryCreator" development="true"/>
<bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
<property name="useSpringBeanBinding" value="true"/>
<property name="viewResolvers">
<list>
<ref bean="viewResolver"/>
</list>
</property>
UserPermissionFirmDetailFBO extends UserPermissionFirm
public class UserPermissionFirm extends AbstractUserPermission {
private static final long serialVersionUID = 1L;
private Long firmId;
private String brokerCd;
private String accountCd;
private boolean cascading;
private boolean supervisor;
private boolean authorisedForSessionCancel;
//used to store supervisor own entering Trader Id
private String enteringTraderId;
private boolean inherited = false;
//Permissions are 'disabled' if they have no sessions
private boolean pseudoDisabledForNoSessions;
private Long exchangeId;
/**
* #return the cascading
*/
public boolean isCascading() {
return cascading;
}
/**
* #param cascading
* the cascading to set
*/
public void setCascading(boolean cascading) {
this.cascading = cascading;
}

Related

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

Why Hibernate 4.3.7.Final saveOrUpdate fires update after every insert ?

In earlier version of Hibernate , saveorUpdate fires insert or update query based on the entity.
But in hibernate 4.3.7 fires update query after every insert.I see both insert and update query.
Domain Object
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="LOGGER")
public class MessageLogger extends BaseDomainObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Column(name = "CP")
private String cpId;
#Column(name = "ACTION")
private String action;
#Column(name = "REQUEST", columnDefinition="text" )
private String request;
#Column(name = "RESPONSE", columnDefinition="text" )
private String response;
#Column(name = "SEND_FROM")
private String sendFrom;
#Column(name = "SEND_TO")
private String sendTo;
public MessageLogger(){
}
public MessageLogger(String cpId,String action,String sendFrom,String sendTo,String request){
this.cpId = cpId;
this.action=action;
this.sendFrom=sendFrom;
this.sendTo=sendTo;
this.request=request;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public String getResponse() {
return response;
}
public String getSendFrom() {
return sendFrom;
}
public void setSendFrom(String sendFrom) {
this.sendFrom = sendFrom;
}
public String getSendTo() {
return sendTo;
}
public void setSendTo(String sendTo) {
this.sendTo = sendTo;
}
public void setResponse(String response) {
this.response = response;
}
public String getCpId() {
return cpId;
}
public void setCpId(String cpId) {
this.cpId = cpId;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
Base Domain Object
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#MappedSuperclass
public abstract class BaseDomainObject implements LastModifiable,Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Version
#Column(name = "VERSION", columnDefinition = "int default 0")
private int version;
#Column(name = "CREATION_TIMESTAMP", nullable = false, insertable = false, updatable = false, columnDefinition = "timestamp default CURRENT_TIMESTAMP")
#Temporal(TemporalType.TIMESTAMP)
private Date creationTimestamp;
#Column(name = "LAST_UPDATED_TIMESTAMP", columnDefinition = "datetime")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdatedTimestamp;
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Date getCreationTimestamp() {
return creationTimestamp;
}
public void setCreationTimestamp(Date creationTimestamp) {
this.creationTimestamp = creationTimestamp;
}
public Date getLastUpdatedTimestamp() {
return lastUpdatedTimestamp;
}
public void setLastUpdatedTimestamp(Date lastUpdatedTimestamp) {
this.lastUpdatedTimestamp = lastUpdatedTimestamp;
}
public Long getId() {
return id;
}
}
DAO Layer
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
public class MessageLoggerDAOImpl
implements MessageLoggerDAO {
#Autowired
SessionFactory sessionFactory;
#Override
#Transactional
public MessageLogger createOrUpdate(MessageLogger messageLogger) {
Session s = sessionFactory.getCurrentSession();
s.saveOrUpdate(messageLogger);
return messageLogger;
}
}
Spring application context configuration :- that configured hibernate session factory
<tx:annotation-driven />
<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.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.my.server.domainobjects" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Log4j Logs:-So when i run createOrUpdate method of MessageLoggerDAOImpl for inserting MessageLogger entity first time , i see below two query
[05 Mar 2015 12:11:15:365] DEBUG SQL::logStatement:109 - insert into LOGGER (LAST_UPDATED_TIMESTAMP, VERSION, ACTION, CP, REQUEST, RESPONSE, SEND_FROM, SEND_TO) values (?, ?, ?, ?, ?, ?, ?, ?)
[05 Mar 2015 12:11:15:546] DEBUG SQL::logStatement:109 - update LOGGER set LAST_UPDATED_TIMESTAMP=?, VERSION=?, ACTION=?, CP=?, REQUEST=?, RESPONSE=?, SEND_FROM=?, SEND_TO=? where ID=? and VERSION=?
Its not the bug.Its my mistake.I have also the event listener on saveorUpdate and i am also saving the object in it.
#Component
public class SaveOrUpdateDateListener extends DefaultSaveOrUpdateEventListener {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void onSaveOrUpdate(SaveOrUpdateEvent event) {
if (event.getObject() instanceof LastModifiable) {
LastModifiable record = (LastModifiable) event.getObject();
record.setLastUpdatedTimestamp(new Date());
}
//super.onSaveOrUpdate(event); // remove this line solve my problem
}
}
Sorry for inconvenience

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, 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

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

Resources