通用类
package com.messaging.dao;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Id;
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 com.messaging.utils.OrderBy;
public abstract class GenericDaoHibernateImpl<T,PK extends Serializable>
implements GenericDao<T,PK> {
private transient final Class<T> clazz;
private transient Field idField;
private transient final List<Field> columnFields = new ArrayList<>();
//private String table;
//private PK key;
@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public GenericDaoHibernateImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
clazz = (Class<T>) pt.getActualTypeArguments()[0];
/*table = clazz.getDeclaredAnnotation(Table.class).name();*/
for(Field field : clazz.getDeclaredFields()) {
if(field.isAnnotationPresent(Column.class)) {
field.setAccessible(true);
if(field.isAnnotationPresent(Id.class))
idField = field;
columnFields.add(field);
}
}
}
@SuppressWarnings("unchecked")
@Override
public PK create(T newInstance) {
return (PK) getSession().save(newInstance);
}
@Override
public void createOrUpdate(T newInstance) {
getSession().saveOrUpdate(newInstance);
}
@Override
public T getById(Serializable id) {
return getSession().get(clazz, id);
}
@Override
public void update(T transientObject) {
getSession().update(transientObject);
}
/*public void update(PK id, T transientObject) {
Session session = getSession();
session.createCriteria(clazz).add(Restrictions.idEq(id));
}*/
@Override
public void delete(T persistentObject) {
getSession().delete(persistentObject);
}
@Override
public void delete(Serializable id) {
T t = getById(id);
getSession().delete(t);
}
@SuppressWarnings("unchecked")
public List<T> getList(T criteria, OrderBy orderBy, Integer page, Integer pageSize) throws IllegalArgumentException, IllegalAccessException {
return getCriteria(criteria,orderBy,page,pageSize).list();
}
@Override
public Map<Serializable, T> getMap(T criteria) throws IllegalArgumentException, IllegalAccessException {
Map<Serializable, T> tMap = new HashMap<>();
@SuppressWarnings("unchecked")
List<T> tList = getCriteria(criteria).list();
for(T t: tList) {
Serializable idVal = (Serializable) idField.get(t);
tMap.put(idVal, t);
}
return tMap;
}
public Criteria getCriteria(T criteria) throws IllegalArgumentException, IllegalAccessException {
return getCriteria(criteria, null, null, null);
}
public Criteria getCriteria(T criteria, Integer pageNumber, Integer pageSize) throws IllegalArgumentException, IllegalAccessException {
return getCriteria(criteria, null, pageNumber, pageSize);
}
public Criteria getCriteria(T criteria, OrderBy orderBy) throws IllegalArgumentException, IllegalAccessException {
return getCriteria(criteria, orderBy, null, null);
}
public Criteria getCriteria(T criteria, OrderBy orderBy,Integer pageNumber, Integer pageSize) throws IllegalArgumentException, IllegalAccessException {
Criteria where = getSession().createCriteria(clazz);
for(Field field : columnFields) {
where.add(Restrictions.eq(field.getDeclaredAnnotation(Column.class).name(), field.get(criteria)));
}
if(orderBy!=null)
where.addOrder(orderBy.getHibernateOrder());
if(pageNumber!=null && pageNumber>0 && pageSize!=null && pageSize>0) {
where.setFirstResult((pageNumber-1)*pageSize);
where.setMaxResults(pageSize);
}
return where;
}
private Session getSession() {
return this.sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
@Override
public T get(T criteria) throws ReflectiveOperationException {
return (T) getCriteria(criteria).uniqueResult();
}
}
简单的Dao实现
package com.messaging.dao;
import org.springframework.stereotype.Repository;
import com.messaging.dto.UserDTO;
@Repository
public class UserHibernateDao extends GenericDaoHibernateImpl<UserDTO, Integer> implements UserDao {
public UserHibernateDao() {
super();
}
@Override
public UserDTO getUserByLogin(String login) throws ReflectiveOperationException {
UserDTO user = new UserDTO();
user.setLogin(login);
return get(user);
}
}
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.1">
<display-name>Messaging Service</display-name>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<servlet>
<servlet-name>messaging-service</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>messaging-service</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>
的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:mvc="http://www.springframework.org/schema/mvc"
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.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.messaging" />
<mvc:annotation-driven />
<tx:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />
</bean>
<import resource="messaging-service-servlet.xml"/>
<import resource="security.xml" />
</beans>
消息接发服务-servlet.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:mvc="http://www.springframework.org/schema/mvc"
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.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<mvc:default-servlet-handler/>
<mvc:resources mapping="/resources/**" location="/resources/bootstrap/"/>
<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/messaging_service?autoReconnect=true" />
<property name="username" value="root" />
<property name="password" value="127" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.messaging.dto"/>
<property name="hibernateProperties">
<props>
<prop key="show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
当我在GenericDaoHibernateImpl中调用方法时,sessionFactory为null。可能是什么问题呢?请帮助