Transactional annotation doesn't work - java

I use spring 3.2.8, hibernate 4. I have an error "org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: createCriteria is not valid without active transaction"
web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>journeys</display-name>
<servlet>
<servlet-name>journeys</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>journeys</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/journeys-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>
journeys-servlet.xml:
<beans xmlns="...">
<context:annotation-config />
<context:component-scan base-package="journeys.*" />
<bean id="viewResolver"
...
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</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://myserver:3306/name" />
<property name="username" value="user" />
<property name="password" value="password" />
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans>
class/hibernate.cfg.xml:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Mapping files -->
<mapping class="journeys.entity.Company"/>
....
</session-factory>
</hibernate-configuration>
CompanyDAO:
package journeys.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import journeys.utils.Pair;
import journeys.entity.Company;
import journeys.entity.Journey;
import journeys.entity.JourneyDeparture;
import journeys.entity.Order;
#Component
public class CompanyDAO extends AbstractDAO<Company> {
#Autowired
private SessionFactory sessionFactory;
public CompanyDAO() {
super(Company.class);
}
#Transactional
#SuppressWarnings("unchecked")
public List<Company> f() {
return (List<Company>)sessionFactory.getCurrentSession().createCriteria(Company.class).list();
}
}
CompanyController:
package journeys.controller;
import journeys.dao.CompanyDAO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping(value = "/company")
public class CompanyController {
#Autowired
CompanyDAO companydao;
#RequestMapping(value = {"", "/", "list"}, method = RequestMethod.GET)
public ModelAndView list() {
ModelAndView model = new ModelAndView("Company/list");
model.addObject("companies", companydao.f());
return model;
}
}

Do the following and the problem goes away:
In your hibernate.cfg.xml add the following property:
<property name="hibernate.current_session_context_class"> org.springframework.orm.hibernate4.SpringSessionContext
</property>
Also remove the line <property name="current_session_context_class">thread</property> that you currently have in your code

A common reason for this that I have seen is the lack of "engine" to apply the effect of #Transactional. Namely, in your pom you need to have a runtime dependency either on cglib or jaspect. Seeing how your tx-manager is defined, it seems you are likely to need cglib.
Edit:
Also, to enable cglib, use:
<tx:annotation-driven proxy-target-class="true" transaction-manager="txManager"/>
instead of just
<tx:annotation-driven transaction-manager="txManager" />

Related

Buling REST with spring-mvc returns 404 The origin server did not find a current

I am trying to build rest api with spring mvc and maven web project; however, when I try to run it on server it returns 404 on any url.
"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."
I've tried to find the solution on the internet and none of them worked for me. I think there might be some mistakes in my configuration but I don't know what. The project is build on eclipse using maven web project, using spring-mvc and hibernate with database mysql. I am kind of confused because there is no error in the log.
Below is my web.xml that I put inside src/main/webapp/WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<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/classes/com/test/restlearning/applicationContext/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is my applicationContext.xml that I put inside src/main/resources/com/test/restlearning/applicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-5.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-5.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-5.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.test.restlearning.controller" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/restlearning" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.test.restlearning.dto"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="personDao" class="com.test.restlearning.dao.impl.PersonDAOImpl">
<constructor-arg ref="sessionFactory" />
</bean>
<bean id="personService" class="com.test.restlearning.service.impl.PersonServiceImpl">
<consrtuctor-arg ref="personDao" />
</bean>
and below is one of my controller
#CrossOrigin
#RestController
#RequestMapping("/persons")
public class PersonController {
#Autowired
#Qualifier("personService")
private PersonService personService;
#RequestMapping(method= RequestMethod.GET, headers = "Accept=application/json")
public Object getAll(HttpServletRequest request, HttpServletResponse response) {
try {
List<Person> persons = personService.getAll();
String url = ServletUtil.unwrap(request);
String json = PersonJSONWrapper.wrap(persons,url);
return ResponseEntity.ok(json);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
public static String getURL() {
return "/persons";
}
public static String getURL(Integer id) {
return "/persons"+id.toString();
}
}
I would be glad if you could point out my mistakes.
It looks like there is no bean PersonService in application context. Add PersonService class to applicationContext.xml as bean.

Access denied for user 'root'#'localhost' (using password: YES), spring-servlet, bean entityManagerFactory

like in topic, but if I will do just persistence.xml file in META-INF with unitName, and do that by this, then everything is good, and my sql query is working, and connection is open.
Here is my view of my project:
project structure
Here is code where I invoke method, my HomeController.java:
#Controller
#RequestMapping("/")
#SessionAttributes("/")
public class HomeController {
#Autowired
private UserDao userDao;
#Autowired
private EmployeeDAO employeeDao;
#RequestMapping(value = {"/dam"}, method = RequestMethod.GET)
public String setupForm(Model model)
{
userDao.getUserByUserId("2");
//employeeDao.getAllEmployees();
return "listEmployeeView";
}
}
Here is UserDao.java:
#Repository
#Transactional
public class UserDao {
#PersistenceContext
private EntityManager entityManager;
public UserModel getUserByUserId(String userId) {
UserModel user = null;
//EntityManagerFactory emf = Persistence.createEntityManagerFactory("movie-unit");
//entityManager = emf.createEntityManager();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<UserModel> cq = cb.createQuery(UserModel.class);
Root<User> userRoot = cq.from(User.class);
cq.multiselect(
userRoot.get("firstName"),
userRoot.get("middleName"),
userRoot.get("lastName"),
userRoot.get("email"),
userRoot.get("userId"),
userRoot.get("password")
);
cq.where(cb.equal(userRoot.get("userId"), userId));
TypedQuery<UserModel> q = entityManager.createQuery(cq);
user = q.getSingleResult();
System.out.print(user.getUserId()+"&"+user.getPassword());
return user;
}
}
here is web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Hibernate JPA Hello World Application</display-name>
<!-- Configuration file for the root application context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-servlet.xml
</param-value>
</context-param>
<!-- Configuration for the DispatcherServlet -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and here is spring-servlet.xml:
<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.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- It register the beans in context and scan the annotations inside beans and activate them -->
<context:component-scan base-package="com.howtodoinjava.demo" />
<!-- This allow for dispatching requests to Controllers by registering
two beans - DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven />
<!-- This helps in mapping the logical view names to directly view files under a certain pre-configured directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- This resolves messages from resource bundles for different locales -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<!-- To validate the posted add employee form -->
<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />
<!-- This produces a container-managed EntityManagerFactory;
rather than application-managed EntityManagerFactory as in case of LocalEntityManagerFactoryBean-->
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.howtodoinjava.demo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<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/baza" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<!-- responsible for registering the necessary Spring components that power annotation-driven transaction management;
such as when #Transactional methods are invoked -->
<tx:annotation-driven />
</beans>
Like I said, if I do entitymanager and entitymanagerfactory in java code which is commented here in UserDao.java with persistence.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.0">
<persistence-unit name="movie-unit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/baza" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
then everythings works fine.
In mysql server I have privileges like this:
Any % -- USAGE
Any localhost no password USAGE
root 127.0.0.1 no password ALL PRIVILEGES
root ::1 no password ALL PRIVILEGES
root localhost with password ALL PRIVILEGES
Where is problem?

JAX-WS web service : Beans not injected : NullPointerException

I have developed a JAX-WS based web-service. I have Web service layer, service layer and a Dao layer. When i call a service method from web service class it gives null pointer exception. The reason is the service class bean is not getting injected.
web-service class:
package com.test.webservice.controller;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.test.salary.service.SalaryService;
#WebService
public class EmployeeSalaryWebService {
private SalaryService salaryService;
/**
* #param salaryService the salaryService to set
*/
#WebMethod(exclude = true)
public void setSalaryService(SalaryService salaryService) {
this.salaryService = salaryService;
}
#WebMethod
public double getEmployeeSalary(String name){
System.out.println("==== Inside getEmployee Salary === "+salaryService );
return salaryService.calculateSalary(name);
}
}
Application-context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="salaryWebService"
class="com.test.webservice.controller.EmployeeSalaryWebService">
<property name="salaryService" ref="salaryService" />
</bean>
<bean name="salaryService" class="com.test.salary.service.SalaryServiceImpl">
<property name="salaryDAO" ref="salaryDAO" />
</bean>
<bean name="salaryDAO" class="com.test.salary.dao.SalaryDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="LOCAL" />
<property name="password" value="abcdef" />
</bean>
</beans>
web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/salaryConfiguration.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Please let me know why the SalaryService salaryService not getting injected.
Your service class and bean in context is two separate things. I believe that you don't get bean from context and just use class, aren't you?
I advice you marking your service class with
#Component
That will make your class to become spring bean.
Then you can use inside following annotation.
#Autowired
This will try to find appropriate bean with annotated element type in spring context.
And don't forget to put into your context.
<context:component-scan base-package="..." />
This will search all classes marked as #Component and add it to spring context as beans.
For more detailed instruction you can check this article
https://www.javacodegeeks.com/2010/11/jaxws-with-spring-and-maven-tutorial.html
Make your SalaryService auto wired as follows:
public class EmployeeSalaryWebService {
#Autowired
private SalaryService salaryService;
....

Spring + JSF with open session pagination not works

I have problem with open session. First of all I use Spring 4.0 + JSF 2.2 + Hibernate 4.3. To provide open session I use org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.
It works partially, I get some entities from database, render the view and lazy loading works correct.
However when after rendering a view I use pagination in p:dataGrid I get lazy initialization exception. How Can I avoid that? I would like that the object will be connected to session as long as the management bean lives. How can I make pagination works without lazy initialization error?
To resolve this problem I try to use check what happen i my management bean. I don't know if I understand it correct but when I use the view scope bean I though that all the time it should be one thread that deal with this bean. But when I print thread id it looks that for every request tomcat use new thread. It's correct behavior? Before, without using spring I use standard open session in view filter and I set hibernate.current_session_context_class to org.hibernate.context.ThreadLocalSessionContext and everything works perfect. I try to use the same setting here but it cause many errors and I read that when I use filter provided by spring I shouldn't mess with it. I use Tomcat 7.0.34 and hibernate-c3p0 4.3.
Part of web.xml
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Hibernate configuration:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>system.properties</value>
</property>
</bean>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- c3p0 props-->
<property name="minPoolSize" value="${c3p0.minPoolSize}" />
<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
<property name="maxStatements" value ="${c3p0.maxStatements}" />
</bean>
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.validator.apply_to_ddl">false</prop>
</props>
</property>
<property name="packagesToScan" value="com.efsf.ostoja" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Managed bean:
package com.efsf.ostoja.clientCase.view;
import com.efsf.ostoja.clientCase.logic.interfaces.ICaseService;
import com.efsf.ostoja.clientCase.model.ClientCase;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import lombok.Getter;
import lombok.Setter;
#ViewScoped
#ManagedBean
public class MarketMB implements Serializable{
#Getter #Setter
private List<ClientCase> cases;
#ManagedProperty(value = "#{caseService}")
#Getter #Setter
private ICaseService service;
#PostConstruct
public void init(){
cases=service.getAllActiveCases();
System.out.println("Id: "+Thread.currentThread().getId());
}
public void test(){
System.out.println("Id2: "+Thread.currentThread().getId());
}
}
Method from service:
#Override
#Transactional
public List<ClientCase> getAllActiveCases(){
return clientCaseDao.findAllByProperty("status", CaseStatus.NEW);
}
Part of my view:
<h:form>
<p:dataGrid value="#{marketMB.cases}" var="c" id="paginatorTable" styleClass="simplePagination" paginator="true" rows="5" columns="1" paginatorTemplate="{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}">
//some div with data here
</p:dataGrid>
</h:form>

hibernate spring class path not found

I am new in spring, and I try to use it with hibernate to create tables from the entity class but it never works, here is my spring-cinfig.xml :
'
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:8889/testeleve"/>
<property name="username" value="root"/>
<property name="password" value="yassine"/>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="Class"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>'
and here is my test class :
'
#Autowired
private static CrudRepository repository;
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
createEleve(22, "Saint", "Peter");
createEleve(23, "Jack", " Dorsey");
createEleve(24, "Sam", "Fox");
}'
and here is the exception:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [TestEleve2/resources/spring-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [TestEleve2/resources/spring-config.xml] cannot be opened because it does not exist
just do one thing put your file spring-config.xml in to the TestEleve2/resources/ path and try to run program again it has to be run.
You should specify where is your spring-config.xml located. Try something like this:
#Autowired
private static CrudRepository repository;
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("/WEB-INF/resources/spring-config.xml");
createEleve(22, "Saint", "Peter");
createEleve(23, "Jack", " Dorsey");
createEleve(24, "Sam", "Fox");
}
Update
mvc-dispatcher-servlet.xml
<import resource="spring-config.xml"/>
Add below code in your web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>YourApp</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>YourApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>YourApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Here, web.xml tries to see YourApp-servlet.xml file which is actually your web.xml.
you need to replace your spring-config.xml to YourApp-servlet.xml .
Here YourApp is your application name. Put it in webapps folder.

Categories