`
jilong-liang
  • 浏览: 472342 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类

SpringMVC+Hibernate全注解整合

阅读更多
package com.org.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.org.dao.UserDao;
import com.org.entity.User;
import com.org.service.UserService;

/**
 *@Author:liangjilong
 *@Date:2014-2-25
 *@Version:1.0
 *@Description:
 */
@Service
public class UserServiceImpl implements UserService{

	@Resource//@Autowired
	private  UserDao userDao;
	
	public List<User> getListUsers() {
		return userDao.getListUsers();
	}
	 
}

 

package com.org.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.org.entity.User;
import com.org.service.UserService;
import com.org.utils.servlet.ServletUtils;

/**
 *@Author:liangjilong
 *@Date:2014-2-25
 *@Version:1.0
 *@Description:
 */
@Controller
public class UserController{

	@Resource
	private UserService userService; 
	
	@RequestMapping(value="/userList1.do")
	public String geUserList1(HttpServletRequest request ,HttpServletResponse response) throws Exception {
		List<User> lists=userService.getListUsers();
		if(lists!=null){
			//request.setAttribute("userList", lists);
			ServletUtils.setRequestValue("userList", lists);
		}
		return "/user/userList";//user文件下的userList.jsp
	}

	
	@RequestMapping(value="/userList2.do")
	public ModelAndView geUserList2(HttpServletRequest request ,HttpServletResponse response) throws Exception {
		List<User> lists=userService.getListUsers();
		if(lists!=null){
			//request.setAttribute("userList", lists);
			ServletUtils.setRequestValue("userList", lists);
		}
		
		return new ModelAndView("/user/userList");
	}

}

 

package com.org.dao;

import java.util.List;

import com.org.entity.User;

/**
 *@Author:liangjilong
 *@Date:2014-2-25
 *@Version:1.0
 *@Description:
 */
public interface UserDao {

	public List<User> getListUsers();

}

 

package com.org.dao.impl;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.org.HibernateDaoImpl;
import com.org.dao.UserDao;
import com.org.entity.User;

/**
 *@Author:liangjilong
 *@Date:2014-2-25
 *@Version:1.0
 *@Description:
 */

@Repository//@Component
@SuppressWarnings("all")
public class UserDaoImpl extends HibernateDaoImpl implements UserDao {
 
	public List<User> getListUsers() {
		String hql="From User";
		//List<User>  lists=hibernateTemplate.find(hql);//方法一
		List<User>  lists=getHibernateTemplate().find(hql);//方法二
		return lists;
	}

}

 

package com.org.service;

import java.util.List;

import com.org.entity.User;

/**
 *@Author:liangjilong
 *@Date:2014-2-25
 *@Version:1.0
 *@Description:
 */
public interface UserService {
	public List<User> getListUsers();
 

}

 

package com.org;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

public class HibernateDaoImpl extends HibernateDaoSupport implements
		IHibernateDao {

	/**
	 * 这个和整合ibatis是一样的
	  */
	@Resource(name = "hibernateTemplate")
	protected HibernateTemplate hibernateTemplate;

	@PostConstruct
	public void initHibernateTemplate() {
		super.setHibernateTemplate(hibernateTemplate);
	}

	public Integer count(final String hql) {
		if (StringUtils.isEmpty(hql)) {
			throw new IllegalStateException("hql is null");
		}
		Object result = this.getHibernateTemplate().execute(
				new HibernateCallback<Object>() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						return session.createQuery(hql).uniqueResult();
					}
				});
		return ((Long) result).intValue();
	}

	public int bulkUpdate(String queryString, Object[] values) {
		return getHibernateTemplate().bulkUpdate(queryString, values);
	}

	public <E> void deleteAll(Collection<E> entities) {
		getHibernateTemplate().deleteAll(entities);
	}

	public Integer count(final String hql, final Object... obj) {
		if (ObjectUtils.isEmpty(obj)) {
			return count(hql);
		} else {
			if (StringUtils.isEmpty(hql)) {
				throw new IllegalStateException("hql is null");
			}
			Object result = this.getHibernateTemplate().execute(
					new HibernateCallback<Object>() {

						public Object doInHibernate(Session session)
								throws HibernateException, SQLException {
							Query query = session.createQuery(hql);
							for (int i = 0; i < obj.length; i++) {
								query.setParameter(i, obj[i]);
							}
							return query.uniqueResult();
						}
					});
			return ((Long) result).intValue();
		}
	}

	public <E> void delete(E entity) {
		getHibernateTemplate().delete(entity);
	}

	public <E> boolean exist(Class<E> c, Serializable id) {
		if (get(c, id) != null)
			return true;
		return false;
	}

	public <E> List<E> find(String queryString) {
		return getHibernateTemplate().find(queryString);
	}

	public <E> List<E> find(Class<E> bean) {
		String hql = "FROM " + bean.getSimpleName();
		return find(hql);
	}

	public List<?> find(String queryString, Object[] values) {
		if (ObjectUtils.isEmpty(values)) {
			return find(queryString);
		} else {
			return getHibernateTemplate().find(queryString, values);
		}
	}

	public <E> E findUniqueEntity(final String queryString,
			final Object... params) {
		if (StringUtils.isEmpty(queryString)) {
			throw new IllegalStateException("queryString is null");
		}
		if (ObjectUtils.isEmpty(params)) {
			return (E) getHibernateTemplate().execute(
					new HibernateCallback<Object>() {
						public Object doInHibernate(Session session) {
							return session.createQuery(queryString)
									.uniqueResult();
						}
					});
		} else {
			return (E) getHibernateTemplate().execute(
					new HibernateCallback<Object>() {
						public Object doInHibernate(Session session) {
							Query query = session.createQuery(queryString);

							for (int i = 0; i < params.length; i++) {
								query.setParameter(i, params[i]);
							}
							return query.uniqueResult();
						}
					});
		}
	}

	public <E> List<E> findByNamedQuery(String queryName) {
		if (StringUtils.isEmpty(queryName)) {
			throw new IllegalArgumentException("queryName is null");
		}
		return getHibernateTemplate().findByNamedQuery(queryName);
	}

	public <E> List<E> findByNamedQuery(String queryName, Object... values) {
		if (ObjectUtils.isEmpty(values)) {
			return this.findByNamedQuery(queryName);
		}
		return getHibernateTemplate().findByNamedQuery(queryName, values);
	}

	public <E> List<E> findByPage(final String hql, final Integer startRow,
			final Integer pageSize, final Object... params) {
		if (StringUtils.isEmpty(hql)) {
			throw new IllegalStateException("hql is null");
		}
		if (ObjectUtils.isEmpty(params)) {
			return getHibernateTemplate().executeFind(
					new HibernateCallback<Object>() {
						public Object doInHibernate(Session session) {
							return session.createQuery(hql)
									.setFirstResult(startRow)
									.setMaxResults(pageSize).list();
						}
					});
		} else {
			return getHibernateTemplate().executeFind(
					new HibernateCallback<Object>() {
						public Object doInHibernate(Session session) {
							Query query = session.createQuery(hql);
							for (int i = 0; i < params.length; i++) {
								query.setParameter(i, params[i]);
							}
							return query.setFirstResult(startRow)
									.setMaxResults(pageSize).list();
						}
					});
		}
	}

	public <E> E get(Class<E> entityClass, Serializable id) {
		this.getHibernateTemplate().setCacheQueries(true);
		return this.getHibernateTemplate().get(entityClass, id);
	}

	public <E> Iterator<E> iterate(String queryString) {
		return getHibernateTemplate().iterate(queryString);
	}

	public <E> Iterator<E> iterate(String queryString, Object... values) {
		return getHibernateTemplate().iterate(queryString, values);
	}

	public <E> E load(Class<E> entityClass, Serializable id) {
		return getHibernateTemplate().load(entityClass, id);
	}

	public <E> void persist(E entity) {
		getHibernateTemplate().persist(entity);
	}

	public <E> void refresh(E entity) {
		getHibernateTemplate().refresh(entity);
	}

	public <E> Serializable save(E entity) {
		if (entity == null) {
			throw new IllegalArgumentException("entity is null");
		}
		return getHibernateTemplate().save(entity);
	}

	public <E> void saveOrUpdate(E entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}

	public <E> void saveOrUpdateAll(Collection<E> entities) {
		getHibernateTemplate().saveOrUpdateAll(entities);
	}

	public <E> void update(E entity) {
		getHibernateTemplate().update(entity);
	}

	public <T> void updateAll(Collection<T> entities) {
		if (CollectionUtils.isEmpty(entities)) {
			throw new IllegalArgumentException("entities is null");
		}
		int i = 0;
		for (Object obj : entities) {
			if (i % 30 == 0) {
				getHibernateTemplate().flush();
				getHibernateTemplate().clear();
			}
			getHibernateTemplate().update(obj);
			i++;
		}
	}

	public <E> void saveAll(Collection<E> entities) {
		if (CollectionUtils.isEmpty(entities)) {
			throw new IllegalArgumentException("entities is null");
		}
		int i = 0;
		for (E obj : entities) {
			if (i % 30 == 0) {
				getHibernateTemplate().flush();
				getHibernateTemplate().clear();
			}
			save(obj);
			i++;
		}
	}

	public <E> List<E> findByPage(String queryString, PageModel pageModel,
			List<?> params) {

		String hql = queryString;
		if (queryString.toLowerCase().indexOf("where") == -1) {
			Matcher m = Pattern.compile("and").matcher(queryString);
			if (m.find()) {
				hql = m.replaceFirst("where");
			} else {
				m = Pattern.compile("AND").matcher(queryString);
				if (m.find()) {
					hql = m.replaceFirst("WHERE");
				}
			}
		}
		int fromIndex = hql.toLowerCase().indexOf("from");
		int orderIndex = hql.toLowerCase().indexOf("group by");
		String hqlCount = "select count(*) "
				+ hql.substring(fromIndex,
						orderIndex > 0 ? orderIndex : hql.length());
		int totalCount = (params == null || params.isEmpty()) ? count(hqlCount)
				: count(hqlCount, params.toArray());
		pageModel.setRecordCount(totalCount);
		if (totalCount == 0) {
			return new ArrayList<E>();
		}
		Object[] temps = (params == null || params.isEmpty()) ? new Object[] {}
				: params.toArray();
		return this.findByPage(hql, pageModel.getStartRow(),
				pageModel.getPageSize(), temps);
	}

}

 

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:oscache="http://www.springmodules.org/schema/oscache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	 	 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
	 	 http://www.springframework.org/schema/context
	 	 http://www.springframework.org/schema/context/spring-context-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 
	 	 http://www.springmodules.org/schema/oscache 
	 	 http://www.springmodules.org/schema/cache/springmodules-oscache.xsd
	 	 http://www.springframework.org/schema/mvc
	 	 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<!--
		 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 
		 mvc:annotation-driven
	--> 
	<mvc:annotation-driven/>
	<!-- 扫描包 -->
	<context:annotation-config/>  
	<context:component-scan base-package="com.org.*" />
	
	<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		  <property name="prefix" value="/jsp/" />
		<property name="suffix" value=".jsp" />  
	</bean>
	
	<!-- 配置jdbc -->
	<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:properties/jdbc.properties</value>
		</property>
	</bean>
	<!-- 配置數據源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!-- 连接池启动时的初始值 -->
        <property name="initialSize" value="1"/>  
        <property name="maxActive" value="500"/>    
        <property name="maxIdle" value="2"/>        
        <property name="minIdle" value="1"/> 
	</bean>
		<!-- 配置sessionFactory 
		注解配置
			org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
		配置形式:
			org.springframework.orm.hibernate3.LocalSessionFactoryBean
		-->
		
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
	 	 <property name="packagesToScan">
			<list>
				<value>com.org.entity</value>
			</list>
		</property>
		 
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
	
	<!-- 配置hibernateTemplate -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- Spring AOP config配置切点 -->  
	<aop:config>
		<aop:pointcut expression="execution(public * com.org.service.*.*(..))"
			id="bussinessService" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService" />
	</aop:config>

	<!-- 配置那个类那个方法用到事务处理 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	
	
<!-- 这个映射配置主要是用来进行静态资源的访问 -->
 <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/> 
 <mvc:resources mapping="/resource/**" location="/resource/" />  
 <mvc:resources mapping="/jsp/**" location="/jsp/" /> 
 
</beans>

 

<?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" id="WebApp_ID" version="2.5">
 <!--
		#####################################配置处理乱码#####################################
	-->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--
		#####################################Spring	MVC配置#################################
		application-servlet.xml,规定:xxx-servlet.xml
	-->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
	 
		<param-name>contextConfigLocation</param-name>
		<!--
			param-name必须要等于contextConfigLocation
			默认的配置
			<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
		-->
		<param-value>classpath:spring-*.xml</param-value>
	</context-param>

	
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-*.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
	<!--
		#####################################struts2配置#######################################
	-->

	<!-- 此配置在使用struts2 -->
 		<filter> 
 			<filter-name>struts2</filter-name> 
 			<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 
 		</filter> 
		<filter-mapping> 
			<filter-name>struts2</filter-name> 
			<url-pattern>/*</url-pattern> 
		</filter-mapping> 
	<!--
		################################使用freemaker模板中启动JSPSupportServlet#############################
	
	<servlet>
		<servlet-name>JspSupportServlet</servlet-name>
		<servlet-class>org.apache.struts2.views.JspSupportServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	-->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 



 

 

 

 源代码

  • 大小: 17.5 KB
  • 大小: 16.5 KB
  • 大小: 64.9 KB
1
0
分享到:
评论
3 楼 jilong-liang 2014-05-08  
shizhangliao 写道
userList1.do 为什么返回404?

请求路径是:http://localhost:8080/项目/userList1.do就OK了
请求路径是:http://localhost:8080/项目/userList2.do就OK了
2 楼 shizhangliao 2014-05-06  
后台没有报任何错误
1 楼 shizhangliao 2014-05-06  
userList1.do 为什么返回404?

相关推荐

Global site tag (gtag.js) - Google Analytics