Announcement Announcement Module
Collapse
No announcement yet.
Persisting with spring and JPA Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Persisting with spring and JPA

    (sorry for my english)
    I crawled over the Internet, I tried out more configuration for my spring web app, because the transaction management and persistance is read-only now. I tired now, please help me.
    I use annotations, and I'd like use it. I use Spring, and I'd like use it, too.

    My appserver is a tomcat 7, with spring 3.1.1 and hibernate 4.1.2 on MySQL 5.

    Following is my config files:

    applicationContext.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans
    	<context:property-placeholder location="classpath:application.properties" />
    <!--     <context:property-placeholder location="classpath:quartz.properties" /> -->
        
    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
      <property name="corePoolSize" value="5" />
      <property name="maxPoolSize" value="10" />
      <property name="queueCapacity" value="25" />
    </bean>
    
    <bean id="taskExecutorExample" class="hu.kepeslap.back.timer.MailScheduler">
      <constructor-arg ref="taskExecutor" />
    </bean>
    
      
        <context:component-scan base-package="hu.kepeslap.back" />
        <context:annotation-config />
        
    	
    	<bean id="reloadableMessageSource"
    		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    		<property name="basename" value="classpath:Messages" />
    		<property name="defaultEncoding" value="UTF-8" />
    	</bean>
    
    	<bean id="springApplicationContext" class="hu.kepeslap.back.spring.SpringApplicationContext" />
    
    	<bean id="mailSenderProps" scope="singleton"
    		class="hu.kepeslap.back.domain.MailSenderProps">
    		<property name="fromEmail" value="${mail.from.email}" />
    		<property name="fromName" value="${mail.from.name}" />
    		<property name="user" value="${mail.user}" />
    		<property name="passwd" value="${mail.passwd}" />
    		<property name="host" value="${mail.host}" />
    		<property name="templatesPath" value="${mail.templates.path}" />
    		<property name="templateFiles" value="${mail.templates.files}" />
    		<property name="subjects" value="${mail.templates.subjects}" />
    	</bean>
    
    	<bean id="fileTransformer" class="hu.kepeslap.back.mail.FileTransformer" />
    
        <bean id="kepeslap_ds"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${database.driver}" />
            <property name="url" value="${database.url}" />
            <property name="username" value="${database.username}" />
            <property name="password" value="${database.password}" />
        </bean>
    
    	<bean id="entityManagerFactory"
    		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    		<property name="persistenceUnitName" value="kepeslap" />
    		<property name="dataSource" ref="kepeslap_ds" />
    		<property name="jpaVendorAdapter">
    			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    				<property name="databasePlatform" value="${database.target}" />
    				<property name="showSql" value="${database.showSql}" />
    				<property name="generateDdl" value="${database.generateDdl}" />
    			</bean>
    		</property>
    	</bean>
    
    	<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    		<property name="scopes">
    			<map>
    				<entry key="view">
    					<bean class="hu.kepeslap.back.spring.ViewScope" />
    				</entry>
    			</map>
    		</property>
    	</bean>
    
    	<bean
    		class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    
    	<bean
    		class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
    
        <bean name="loginService" class="hu.kepeslap.user.LoginService"/>
    
    	<security:http auto-config="true" security="none"
    		pattern="/login.jsf" />
    
    	<security:http auto-config="true" access-denied-page="/error/access_denied.jsf">
    		<security:intercept-url pattern="/user/**"
    			access="ROLE_USER" />
    		<security:intercept-url pattern="/admin/**"
    			access="ROLE_ADMIN" />
    		<security:form-login login-page="/login.jsf"
    			default-target-url="/index.html" always-use-default-target="false"
    			authentication-failure-url="/login.jsf?authfailed=true" />
    		<security:logout logout-url="/logout"
    			logout-success-url="/index.htm" />
    	</security:http>
    
    	<security:authentication-manager>
    		<security:authentication-provider
    			user-service-ref="loginService" />
    	</security:authentication-manager>
     
    <!--
    	<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	    <property name="dataSource" ref="kepeslap_ds" />
    	</bean>
    -->
    
        <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>
    
        <tx:annotation-driven transaction-manager="txManager" /> <!-- transactionManager -->
     
    <!--  <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" /> -->
    
    </beans>
    I'd like user entityManagerFactory if possible, and not Hibernate configured DataSource persistance.

    persistence.xml
    Code:
    <?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">
      <!-- JTA -->
      <persistence-unit name="kepeslap" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <non-jta-data-source>kepeslap_ds</non-jta-data-source>
        <class>hu.kepeslap.back.domain.User</class>
        <class>hu.kepeslap.back.domain.UserRole</class>
        <class>hu.kepeslap.back.domain.Category</class>
        <class>hu.kepeslap.back.domain.Card</class>
        <class>hu.kepeslap.back.domain.Mail</class>
        <class>hu.kepeslap.back.domain.Image</class>
        <class>hu.kepeslap.back.domain.Voucher</class>
        <class>hu.kepeslap.back.domain.MailScheduleEvent</class>
        <class>hu.kepeslap.back.domain.Contact</class>
        <class>hu.kepeslap.back.domain.Illustrious</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
      </persistence-unit>
    </persistence>
    dispatcher-servlet.xml
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans>
    
        <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsf" />
    
        <bean id="messageSource"
            class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="basenames">
                <list>
                    <value>classpath:messages</value>
                </list>
            </property>
            <property name="defaultEncoding" value="UTF-8" />
        </bean>
     
     <!-- MVC 20120701 -->
        <mvc:view-controller path="/" view-name="welcome"/>
        <mvc:annotation-driven />
        <mvc:resources location="/resource/" mapping="/resource/**" />
        
        <context:component-scan base-package="hu.kepeslap.*" />
        <context:annotation-config />
    <!-- 
        <tx:advice id="txUser" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="get*" read-only="true" />
                <tx:method name="updateCurrentUser" propagation="REQUIRES_NEW" read-only="false"/>
                <tx:method name="persist" propagation="REQUIRED" read-only="false"/>
                <tx:method name="update*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="delete*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="create*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="set*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    
        <tx:advice id="txMail" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="get*" read-only="true" />
                <tx:method name="saveMail" propagation="REQUIRES_NEW" read-only="false" />
                <tx:method name="persist" propagation="REQUIRED" read-only="false"/>
                <tx:method name="update*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="delete*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="create*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="set*" propagation="REQUIRED" read-only="false"/>
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    
        <aop:config>
            <aop:pointcut id="mailManager"
                expression="execution(* hu.kepeslap.middle.manager.MailManager.*(..))" />
            <aop:pointcut id="userService"
                expression="execution(* hu.kepeslap.middle.service.UserServiceImpl.*(..))" />
            <aop:advisor pointcut-ref="mailManager" advice-ref="txMail" />
            <aop:advisor pointcut-ref="userService" advice-ref="txUser" />
        </aop:config>
    -->
    </beans>

  • #2
    When I use AOP, I get fallowing exception on @Autowired property:
    Code:
    Error creating bean with name 'cardController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private hu.kepeslap.middle.manager.FavouriteImagesManager hu.kepeslap.front.controll.CardController.favouriteImagesManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'favouriteImagesManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private hu.kepeslap.middle.service.UserService hu.kepeslap.middle.manager.FavouriteImagesManager.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [hu.kepeslap.middle.service.UserService] 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)}
    my web.xml:
    Code:
    <?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">
    	<context-param>
    		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    		<param-value>client</param-value>
    	</context-param>
    
    	<context-param>
    		<param-name>javax.faces.PROJECT_STAGE</param-name>
    		<param-value>Production</param-value>
    	</context-param>
    
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:applicationContext.xml</param-value>
    	</context-param>
    	
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    	
    	<listener>
    		<listener-class>
    			org.springframework.web.context.request.RequestContextListener</listener-class>
    	</listener>
    	
    	<listener>
    		<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    	</listener>
    	
    	<filter-mapping>
    		<filter-name>CharacterEncodingFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    
    	<filter>
    		<filter-name>Spring JPA Filter</filter-name>
    		<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    	</filter>
    	
    	<filter-mapping>
    		<filter-name>Spring JPA Filter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    	
    	<filter>
    		<filter-name>springSecurityFilterChain</filter-name>
    		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    	</filter>
    	
    	<filter-mapping>
    		<filter-name>springSecurityFilterChain</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    	
    	<filter>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
            <init-param>
                <param-name>thresholdSize</param-name>
                <param-value>2097152</param-value>
            </init-param>      
        </filter>
        <filter-mapping>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
            <servlet-name>Faces Servlet</servlet-name>
        </filter-mapping>  
        
    	<servlet>
    		<servlet-name>Faces Servlet</servlet-name>
    		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    	
    	<servlet-mapping>
    		<servlet-name>Faces Servlet</servlet-name>
    		<url-pattern>*.jsf</url-pattern>
    	</servlet-mapping>
    	
    	<servlet>
    		<servlet-name>dispatcher</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                    /WEB-INF/dispatcher-servlet.xml
                </param-value>
            </init-param>
    		<load-on-startup>2</load-on-startup>
    	</servlet>
    	
    	<servlet-mapping>
    		<servlet-name>dispatcher</servlet-name>
    		<url-pattern>*.htm</url-pattern>
    	</servlet-mapping>
    		
    	<context-param>
    		<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    		<param-value>resources.application</param-value>
    	</context-param>
    
    	<listener>
    		<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    	</listener>
    	
    	<welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
    
    </web-app>

    Comment


    • #3
      I made a generic DAO object that use @Transactional:
      Code:
      package hu.kepeslap.back.dao;
      
      public abstract class GenericDAOWithJPA<T, ID extends Serializable> implements GenericDAO<T, ID> {
      
          private Class<T> persistentClass;
          private User userFilter;
      
          protected static Logger log = Logger.getLogger("hu.kepeslap"); // RootLogger()
      
          @PersistenceContext(unitName = "kepeslap")
          protected EntityManager entityManager;
          
          public GenericDAOWithJPA(Class<T> persistentClass) {
              this.persistentClass = persistentClass;
              log.debug("[Generic] GenericDAOWithJPA construction finished. PersistClass: " + this.persistentClass.getSimpleName());
          }
      
          public Class<T> getPersistentClass() {
              return persistentClass;
          }
      
          @Transactional(readOnly = true)
          public T loadById(ID id) {
              return entityManager.find(persistentClass, id);
          }
      
          @Transactional
          public void persist(T entity) {
              entityManager.persist(entity);
          }
      
          @Transactional
          public void update(T entity) {
              entityManager.merge(entity);
          }
      
          @Transactional
          public void delete(T entity) {
              entityManager.remove(entity);
          }
      
          @Transactional(readOnly = true)
          @SuppressWarnings("unchecked")
          public List<T> loadAll() {
              return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
          }
      
          public void setUserFilter(User loggedInUser) {
              this.userFilter = loggedInUser;
              if (loggedInUser != null) {
                  log.debug("[" + getClass().getSimpleName() + "] setUserFilter = {" + loggedInUser + ": id=" + loggedInUser.getUserId() + "}");
              } else {
                  log.debug("[" + getClass().getSimpleName() + "] setUserFilter = {null}");
              }
          }
      
          public User getUserFilter() {
              return userFilter;
          }
      
          @Transactional
          public void deleteAllByUserId(Long userId) {
              Query query = entityManager.createQuery("Delete from " + persistentClass.getSimpleName() + " where userId = :userId");
              query.setParameter("userId", userId);
              query.executeUpdate();
          }
      
          public EntityManager getEntityManager() {
              return entityManager;
          }
      
          public void setEntityManager(EntityManager entityManager) {
              this.entityManager = entityManager;
          }
      
          @SuppressWarnings("unchecked")
          @Transactional(readOnly = true)
          public List<T> loadLazy(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
              log.debug("[Generic] "+getClass().getSimpleName()+".loadLazy {userFilter = "+userFilter+", first = "+first+", pageSize = "+pageSize+"}");
              String where = "";
              if (userFilter != null) {
                  where = "userId = " + String.valueOf(userFilter.getUserId());
                  log.debug("[Generic] ["+getClass().getSimpleName()+".loadLazy()] setUserFilter = {"+userFilter+": id="+userFilter.getUserId()+"}");
              } else {
                  log.debug("[Generic] [" + getClass().getSimpleName() + ".loadLazy()] setUserFilter = {null}");
              }
              if (filters != null) {
                  for (Map.Entry<String, String> e : filters.entrySet())
                      where += (where.length() > 0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
              }
              Query lazy = entityManager.createQuery("Select c from " + persistentClass.getSimpleName() + " c" + (where.length() > 0 ? " where " + where : "") + (sortField != null && sortOrder != null ? " order by " + sortField + " " + sortOrder : ""));
              lazy.setFirstResult(first);
              lazy.setMaxResults(pageSize);
              
              return lazy.getResultList();
          }
      
          @Transactional(readOnly = true)
          public BigInteger getRowCount(Map<String, String> filters) {
              String where = "";
              if (userFilter != null) {
                  where = "userId = " + String.valueOf(userFilter.getUserId());
              }
              if (filters != null) {
                  for (Map.Entry<String, String> e : filters.entrySet()) {
                      where += (where.length() > 0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
                  }
              }
              BigInteger result = (BigInteger)this.entityManager.createNativeQuery("select count(*) from " + persistentClass.getSimpleName() + " c" + (where.length() > 0 ? " where " + where : "")).getSingleResult();
              log.debug("[Generic] "+getClass().getSimpleName()+".rowCount {userFilter = "+userFilter+" , count = "+String.valueOf(result)+"}");
              return  result;
          }
      
      }
      The UserServiceImpl.java:
      Code:
      package hu.kepeslap.middle.service;
      
      //@ManagedBean(name="userService")
      @Service("userService")
      //@SessionScoped
      @Scope("session")
      public class UserServiceImpl extends GenericServiceImpl<User,Long> implements UserService {
      
          @Autowired
          private UserDAO userDAO;
          
          @Autowired
          private JpaTransactionManager txManager;
      
      
          @Transactional
          public void updateCurrentUser() throws EntityExistsException {
              if (currentObject != null) {
                 
                  //EntityManager entityManager = txManager.getEntityManagerFactory().createEntityManager();
                  //txManager.getTransaction().begin();
      
                  if (((User)currentObject).getUserId() != null) {
                      try {
      
                          List<User> exists = null;
                          exists = ((UserDAO)genericDAO).findByEmailAddress(((User)currentObject).getEmailAddress(), true);
                          if (exists != null) {
                              Iterator<User> iter = exists.iterator();
                              while (iter.hasNext()) {
                                  User user = iter.next();
                                  if (user.getUserId() != ((User)currentObject).getUserId()) {
                                      throw new EntityExistsException("User exits with same e-mail");
                                  }
                              }
                              ((UserDAO)genericDAO).update((User)currentObject);
                          }
      
                      } catch (UsernameNotFoundException ex) {
                          ((UserDAO)genericDAO).update((User)currentObject);
                      }
                  } else {
                      ((UserDAO)genericDAO).persist((User)currentObject);
                  }
                  //entityManager.getTransaction().commit();
              }
          }
      }
      Thanx for help me.

      Comment


      • #4
        Did you consider Spring Data ?
        IMO, it's easier and you get rid of the DAO layer. http://www.springsource.org/spring-data/jpa

        Comment


        • #5
          I really don't understand what's your problem. By the way ... I think you miss UserDAO.

          Can you be more specific? If so, maybe we can help you ...

          Originally posted by pzoli View Post
          I made a generic DAO object that use @Transactional:
          Code:
          package hu.kepeslap.back.dao;
          
          public abstract class GenericDAOWithJPA<T, ID extends Serializable> implements GenericDAO<T, ID> {
          
              private Class<T> persistentClass;
              private User userFilter;
          
              protected static Logger log = Logger.getLogger("hu.kepeslap"); // RootLogger()
          
              @PersistenceContext(unitName = "kepeslap")
              protected EntityManager entityManager;
              
              public GenericDAOWithJPA(Class<T> persistentClass) {
                  this.persistentClass = persistentClass;
                  log.debug("[Generic] GenericDAOWithJPA construction finished. PersistClass: " + this.persistentClass.getSimpleName());
              }
          
              public Class<T> getPersistentClass() {
                  return persistentClass;
              }
          
              @Transactional(readOnly = true)
              public T loadById(ID id) {
                  return entityManager.find(persistentClass, id);
              }
          
              @Transactional
              public void persist(T entity) {
                  entityManager.persist(entity);
              }
          
              @Transactional
              public void update(T entity) {
                  entityManager.merge(entity);
              }
          
              @Transactional
              public void delete(T entity) {
                  entityManager.remove(entity);
              }
          
              @Transactional(readOnly = true)
              @SuppressWarnings("unchecked")
              public List<T> loadAll() {
                  return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
              }
          
              public void setUserFilter(User loggedInUser) {
                  this.userFilter = loggedInUser;
                  if (loggedInUser != null) {
                      log.debug("[" + getClass().getSimpleName() + "] setUserFilter = {" + loggedInUser + ": id=" + loggedInUser.getUserId() + "}");
                  } else {
                      log.debug("[" + getClass().getSimpleName() + "] setUserFilter = {null}");
                  }
              }
          
              public User getUserFilter() {
                  return userFilter;
              }
          
              @Transactional
              public void deleteAllByUserId(Long userId) {
                  Query query = entityManager.createQuery("Delete from " + persistentClass.getSimpleName() + " where userId = :userId");
                  query.setParameter("userId", userId);
                  query.executeUpdate();
              }
          
              public EntityManager getEntityManager() {
                  return entityManager;
              }
          
              public void setEntityManager(EntityManager entityManager) {
                  this.entityManager = entityManager;
              }
          
              @SuppressWarnings("unchecked")
              @Transactional(readOnly = true)
              public List<T> loadLazy(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
                  log.debug("[Generic] "+getClass().getSimpleName()+".loadLazy {userFilter = "+userFilter+", first = "+first+", pageSize = "+pageSize+"}");
                  String where = "";
                  if (userFilter != null) {
                      where = "userId = " + String.valueOf(userFilter.getUserId());
                      log.debug("[Generic] ["+getClass().getSimpleName()+".loadLazy()] setUserFilter = {"+userFilter+": id="+userFilter.getUserId()+"}");
                  } else {
                      log.debug("[Generic] [" + getClass().getSimpleName() + ".loadLazy()] setUserFilter = {null}");
                  }
                  if (filters != null) {
                      for (Map.Entry<String, String> e : filters.entrySet())
                          where += (where.length() > 0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
                  }
                  Query lazy = entityManager.createQuery("Select c from " + persistentClass.getSimpleName() + " c" + (where.length() > 0 ? " where " + where : "") + (sortField != null && sortOrder != null ? " order by " + sortField + " " + sortOrder : ""));
                  lazy.setFirstResult(first);
                  lazy.setMaxResults(pageSize);
                  
                  return lazy.getResultList();
              }
          
              @Transactional(readOnly = true)
              public BigInteger getRowCount(Map<String, String> filters) {
                  String where = "";
                  if (userFilter != null) {
                      where = "userId = " + String.valueOf(userFilter.getUserId());
                  }
                  if (filters != null) {
                      for (Map.Entry<String, String> e : filters.entrySet()) {
                          where += (where.length() > 0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
                      }
                  }
                  BigInteger result = (BigInteger)this.entityManager.createNativeQuery("select count(*) from " + persistentClass.getSimpleName() + " c" + (where.length() > 0 ? " where " + where : "")).getSingleResult();
                  log.debug("[Generic] "+getClass().getSimpleName()+".rowCount {userFilter = "+userFilter+" , count = "+String.valueOf(result)+"}");
                  return  result;
              }
          
          }
          The UserServiceImpl.java:
          Code:
          package hu.kepeslap.middle.service;
          
          //@ManagedBean(name="userService")
          @Service("userService")
          //@SessionScoped
          @Scope("session")
          public class UserServiceImpl extends GenericServiceImpl<User,Long> implements UserService {
          
              @Autowired
              private UserDAO userDAO;
              
              @Autowired
              private JpaTransactionManager txManager;
          
          
              @Transactional
              public void updateCurrentUser() throws EntityExistsException {
                  if (currentObject != null) {
                     
                      //EntityManager entityManager = txManager.getEntityManagerFactory().createEntityManager();
                      //txManager.getTransaction().begin();
          
                      if (((User)currentObject).getUserId() != null) {
                          try {
          
                              List<User> exists = null;
                              exists = ((UserDAO)genericDAO).findByEmailAddress(((User)currentObject).getEmailAddress(), true);
                              if (exists != null) {
                                  Iterator<User> iter = exists.iterator();
                                  while (iter.hasNext()) {
                                      User user = iter.next();
                                      if (user.getUserId() != ((User)currentObject).getUserId()) {
                                          throw new EntityExistsException("User exits with same e-mail");
                                      }
                                  }
                                  ((UserDAO)genericDAO).update((User)currentObject);
                              }
          
                          } catch (UsernameNotFoundException ex) {
                              ((UserDAO)genericDAO).update((User)currentObject);
                          }
                      } else {
                          ((UserDAO)genericDAO).persist((User)currentObject);
                      }
                      //entityManager.getTransaction().commit();
                  }
              }
          }
          Thanx for help me.

          Comment


          • #6
            Originally posted by psabbate View Post
            I really don't understand what's your problem. By the way ... I think you miss UserDAO.

            Can you be more specific? If so, maybe we can help you ...
            Yes, I have a UserDAO bean:

            Code:
            package hu.kepeslap.back.dao;
            
            import hu.kepeslap.back.domain.User;
            
            //@ManagedBean
            @Repository
            @Scope("session")
            public class UserDAOWithJPA extends GenericDAOWithJPA<User,Long> implements UserDAO {
            
                @SuppressWarnings("unchecked")
                public UserDAOWithJPA(){
                    super(User.class);
                    log.debug("[Repository] UserDAOWithJPA construction finished");
                }
            
                @SuppressWarnings("unchecked")
                @Override
                public List<User> findByEmailAddress(String emailAddress, boolean enabled) throws UsernameNotFoundException {
                    List<User> user = null;
                    try {
                      user = entityManager.createQuery("from User where emailAddress = :emailAddress and enabled = :enabled", User.class)
                                .setParameter("emailAddress", emailAddress)
                                .setParameter("enabled", enabled)
                                .getResultList();
                    } catch (NoResultException ex) {
                        throw new UsernameNotFoundException(ex.getLocalizedMessage());
                    }
                    return user;
                }
            
                @SuppressWarnings("unchecked")
                public List<User> findByUserName(String name) {
                    Query query = entityManager.createQuery("Select u from User u where u.name LIKE :name");
                    query.setParameter("name", name + "%");
            
                    return query.getResultList();
                }
            
                public void setEnabled(User user, boolean enabled) {
                    user.setEnabled(enabled);
                    entityManager.merge(user);
                }
            
            }
            GenericDAOWithJPA implements base persistence methods. But I can't write to database with them. It's looks like data saved well to table, but after refresh the view, old version of entity come back to data table on all table view. So, my problem is the read-only like persistence configuration. Somewhere I lost JPA with spring.

            I tried simple javax.faces ManagedBean and ManagedProperty, but I'd like finish it with Spring. I made some test application from https://src.springframework.org/svn/spring-samples/ . It's very userfull. But now I'm not on the top, and I need some help to continue.

            The question is:
            - Where is the mistake in my configuration?
            - How can I get back the r/w config or worked @Transactional(readOnly=false) jpa?
            - What is AOP error send me back, and how can I modify code to get well @Autowired UserServiceImpl ?
            Last edited by pzoli; Aug 18th, 2012, 12:38 AM.

            Comment


            • #7
              Originally posted by NicoTexas View Post
              Did you consider Spring Data ?
              IMO, it's easier and you get rid of the DAO layer. http://www.springsource.org/spring-data/jpa
              Dear NicoTexas!

              Thank you for response.
              I visited this modul, and I think this can be a solution for a "started now" application.
              I wont like use new module, only want a modified configuration or similar simpliest solution.

              Comment

              Working...
              X