<?xml version="1.0" encoding="UTF-8"?> <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>helpu</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/app-config.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> /WEB-INF/spring/mvc-config.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> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app>
app-config.xml[Spring的数据访问配置文件]
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost/helpu?useUnicode=true&characterEncoding=utf-8</value></property> <property name="username"><value>root</value></property> <property name="password"><value></value></property> </bean> <!-- Hibernate SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"><ref local="dataSource"/></property> <property name="packagesToScan" value="com.helpu" /> <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> </props> </property> </bean> <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"><ref local="sessionFactory"/></property> </bean> <context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
mvc-config.xml [spring mvc 配置文件]
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- Scans the classpath of this application for @Components to deploy as beans --> <context:component-scan base-package="com.helpu" > <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <!-- Configures the @Controller programming model --> <mvc:annotation-driven /> <!-- misc --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="suffix" value=".jsp"/> </bean> <!-- Configures Hibernate - Database Config <import resource="db-config.xml" />--> </beans>
DAO接口[]
package com.helpu.dao; import java.util.List; /** * * @author apple * @description * @param <T> */ public interface IDAO<T> { T get(int id); T add(T obj); boolean delete(T obj); T update(T obj) throws Exception; List<T> query(String hql,Object... params); int count(); int count(String hql,Object...params); List<T> query(String hql,int page,int pagesize,Object... params); }
dao实现
package com.helpu.dao.impl; import java.lang.reflect.ParameterizedType; import java.sql.SQLException; import java.util.List; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.annotations.FlushModeType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateAccessor; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.HibernateTemplate; import com.helpu.dao.IDAO; public abstract class DAOImpl<T> implements IDAO<T> { protected HibernateTemplate hibernateTemplate; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { hibernateTemplate = new HibernateTemplate(sessionFactory); //hibernateTemplate.setFlushMode(HibernateAccessor.FLUSH_AUTO); } public T add(T obj) { hibernateTemplate.save(obj); return obj; } public boolean delete(T obj) { try{ hibernateTemplate.delete(obj); return true; }catch (Exception e) { return false; } } @SuppressWarnings("unchecked") public T get(int id) { Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; return hibernateTemplate.get(clazz, id); } public T update(T obj) throws Exception { hibernateTemplate.update(obj); return obj; } @SuppressWarnings("unchecked") @Override public List<T> query(String hql, Object... params) { return (List<T>) hibernateTemplate.find(hql, params); } @SuppressWarnings("unchecked") @Override public int count() { Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; String hql = "select count(*) from " + clazz.getName(); return count(hql); } @Override @SuppressWarnings("rawtypes") public int count(String hql,Object...params) { List result = hibernateTemplate.find(hql,params); return ((Long) result.get(0)).intValue(); } @Override public List<T> query(final String hql, final int page, final int pagesize, final Object... params) { @SuppressWarnings("unchecked") List<T> result = hibernateTemplate.executeFind(new HibernateCallback<List<T>>() { @Override public List<T> doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.createQuery(hql); q.setFirstResult(page*pagesize-pagesize); q.setMaxResults(pagesize); int i=0; for (Object o : params) { q.setParameter(i, o); i++; } return q.list(); } }); return result; } }
实际的DAO以及其接口
package com.helpu.dao; import com.helpu.model.Category; public interface ICategoryDAO extends IDAO<Category> { } package com.helpu.dao.impl; import org.springframework.stereotype.Repository; import com.helpu.dao.ICategoryDAO; import com.helpu.model.Category; @Repository public class CategoryDAO extends DAOImpl<Category> implements ICategoryDAO { }
Service层
package com.helpu.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.helpu.dao.ICategoryDAO; import com.helpu.helper.JsonDataWrapper; import com.helpu.model.Category; @Service public class CategoryService { @Autowired() @Qualifier("categoryDAO") private ICategoryDAO categoryDAO; public void setCategoryDAO(ICategoryDAO categoryDAO) { this.categoryDAO = categoryDAO; } @Transactional(readOnly=true) public JsonDataWrapper<Category> pages(int page,int pagesize){ int total = categoryDAO.count(); List<Category> rows = categoryDAO.query("from Category", page, pagesize); JsonDataWrapper<Category> categories = new JsonDataWrapper<Category>(page, total, rows); return categories; } @Transactional public void update(Category c) throws Exception { this.categoryDAO.update(c); } @Transactional public void save(Category c){ this.categoryDAO.add(c); } @Transactional public void delete(int id) { this.categoryDAO.delete(this.categoryDAO.get(id)); } @Transactional(readOnly=true) public Category getCategory(int id) { return this.categoryDAO.get(id); } @Transactional(readOnly=true) public List<Category> all() { return this.categoryDAO.query("from Category"); } }
spring的controller写法
package com.helpu.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.helpu.model.Category; import com.helpu.service.CategoryService; @Controller @RequestMapping("/category") public class SoftwareCategoryController { @RequestMapping("/show.do") public @ResponseBody Category show(@RequestParam int id){ return this.categoryService.getCategory(id); } public void setCategoryService(CategoryService categoryService) { this.categoryService = categoryService; } @Autowired private CategoryService categoryService; }