Erreur NullPointerExecption pour SessionFactory
Bonjour,
Je suis en train de commencer un projet web utilisant Spring 3.1.1 et Hibernate.
Les dépendances de librairie sont gérés par Maven.
J'utilise certaines annotations pour éviter de déclarer tous mes contrôleurs, mes vues. Par contre, je ne sais pas si je les utilise correctement en ce qui concerne les Dao.
Comme beaucoup je n'aime pas recoder plein de fois les mêmes fonctions. Alors j'ai décidé de faire des classes génériques :
- Model : GenericEntity
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class GenericEntity implements Serializable {
/**
* Element Identified an Entity
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
} |
- Dao : GenericEntityDao
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import java.util.List;
public interface GenericEntityDao<T extends GenericEntity> {
T save(T entity);
T merge(T entity);
void delete(T entity);
T getById(Long id);
List<T> getAll();
List<T> getAllWithPagination(int start, int count);
int count();
Class<T> getEntityClass();
} |
- Implémenation Dao : HibernateGenericEntityDao
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
@Transactional
public abstract class HibernateGenericEntityDao<T extends GenericEntity> implements GenericEntityDao<T> {
@Autowired
private SessionFactory sessionFactory;
private Class<T> entityClass;
public HibernateGenericEntityDao(Class<T> entityClass) {
this.entityClass = entityClass;
}
public T save(T entity) {
getSession().saveOrUpdate(entity);
return entity;
}
public T merge(T entity) {
return (T) getSession().merge(entity);
}
public void delete(T entity) {
getSession().delete(entity);
}
public T getById(Long id) {
return (T) getSession().get(getEntityClass(), id);
}
public List<T> getAll() {
return createCriteria().list();
}
public List<T> getAllWithPagination(int start, int count) {
return createCriteria()
.setFirstResult(start)
.setMaxResults(count)
.list();
}
public int count() {
Criteria criteria = createCriteria();
criteria.setProjection(Projections.rowCount());
return ((Number) criteria.list().get(0)).intValue();
}
public Class<T> getEntityClass() {
return this.entityClass;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
protected Criteria createCriteria() {
return getSession().createCriteria(getEntityClass());
}
} |
Voici les fichiers de configurations :
- web.xml
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
</web-app> |
- applicationContext.xml
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/properties/jdbc.properties" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="{jdbc.password}" />
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.shouwy.series.dao" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<!--Transactional-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" autowire="byName">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--DAO-->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans> |
- dispatcher-servlet.xml
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.shouwy.series" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans> |
Maintenant il manque le model et le Controller:
- Controller : SeriesController
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import com.shouwy.series.dao.hibernate.HibernateSerieDao;
import com.shouwy.series.model.Serie;
import java.util.ArrayList;
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
public class SeriesController {
@RequestMapping(value = "/series", method = RequestMethod.GET)
public ModelAndView series(){
HibernateSerieDao hsd = new HibernateSerieDao();
ArrayList<Serie> listSeries = (ArrayList<Serie>) hsd.getAll();
ModelAndView model = new ModelAndView();
model.setViewName("listseries");
model.addObject("list", listSeries);
return model;
}
} |
- Model : Serie
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import com.shouwy.series.dao.generic.GenericEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "serie")
public class Serie extends GenericEntity {
@Column(name = "Nom")
private String nom;
@Column(name = "Synopsis")
private String synopsis;
@Column(name = "IdType")
private int idType;
@Column(name = "idEtat")
private int idEtat;
@Column(name = "idEtatPersonnel")
private int idEtatPersonnel;
} |
Je ne sais pas vraiment si il s'agit d'une erreur de configuration de spring, hibernate ou si il s'agit d'une erreur/oubli dans mon code.
Je vous ai mis en rouge la ligne qui me crée le NullPointerException