`
zjnbshifox
  • 浏览: 316585 次
  • 性别: Icon_minigender_1
  • 来自: 宁波
社区版块
存档分类
最新评论

Spring MVC3 Hibernate3 Annotation

    博客分类:
  • Java
阅读更多
web.xml
<?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&amp;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;
}
分享到:
评论

相关推荐

    Spring MVC + Hibernate +Annotation

    Spring MVC和Hibernate是Java开发中两个非常重要的框架,它们分别负责Web应用的模型-视图-控制器(MVC)架构和对象关系映射(ORM)。本教程将详细讲解如何将这两个框架结合使用,并通过注解简化配置过程。 首先,...

    基于注解的Spring MVC+Hibernate简单入门

    ### 基于注解的Spring MVC+Hibernate简单入门 #### 概述 本文主要介绍如何使用基于注解的方式构建Spring MVC与Hibernate相结合的应用程序。这种方式不仅简化了配置过程,而且提高了开发效率。我们将通过一个具体的...

    Spring4 MVC Hibernate4集成(Annotation)

    Spring4 MVC Hibernate4集成,使用Annotation,封装dao层和service层。 环境: spring 4.0.3.RELEASE hibernate 4.3.5.Final mysql 5.1.29

    springmvc + hibernate annotation 配置

    在本篇文章中,我们将详细探讨如何将Spring MVC与Hibernate结合,并利用注解(Annotation)进行配置。 首先,让我们了解这两个框架的基本概念。Spring MVC是Spring框架的一部分,它是一个用于构建Web应用的模型-...

    Struts2+Spring2+Hibernate3+Annotation所需JAR包

    ### Struts2+Spring2+Hibernate3+Annotation所需JAR包详解 在Java Web开发领域,Struts2、Spring2和Hibernate3是三个非常重要的框架,它们分别负责Web层、业务逻辑层和服务持久化层的功能实现。为了更好地整合这三...

    hibernate annotation spring 中文参考文档

    "spring-framework-reference"文档中详细介绍了Spring的核心特性,包括Bean的声明和管理、Spring MVC的使用、数据访问支持(如JDBC、Hibernate集成)以及Spring的其他模块,如Spring Boot和Spring Security。...

    hibernate和spring MVC配置整合

    **hibernate与Spring MVC配置整合详解** 在Java Web开发中,Spring MVC作为控制器层,负责处理用户请求,而Hibernate作为持久化框架,用于管理数据库操作。将这两者结合使用,可以实现MVC架构的高效数据访问。下面...

    JavaEE多层架构Struts2+Spring3+Hibernate3+Ajax的整合

    ### JavaEE多层架构Struts2+Spring3+Hibernate3+Ajax的整合 ...总之,Struts2+Spring3+Hibernate3+Ajax 的整合框架结合了 MVC 模式的优点和现代 Web 开发的最佳实践,是构建高质量企业级应用的强大工具。

    sping hibernate Annotation(注释配置) demo(例子)

    总结来说,这个 "Spring Hibernate Annotation demo" 展示了如何在 Spring 框架中使用注解配置来管理依赖,以及如何利用 Hibernate 的注解进行数据持久化。同时,它还涉及到了 Flex 前端与后端的交互。通过学习这个 ...

    struts2+spring2+hibernate3 Annotation的整合

    本文将详细解析"Struts2+Spring2+Hibernate3 Annotation的整合"这一主题,主要涵盖以下几个方面: 1. **Struts2框架**:Struts2是一个基于MVC设计模式的Web应用框架,用于简化Java Web应用程序的开发。它的主要功能...

    Struts2+Spring2.5+Hibernate3+annotation 整合程序

    这个"Struts2+Spring2.5+Hibernate3+annotation"整合程序是为了实现高效、灵活和松耦合的Web应用架构。下面将详细介绍这三个框架的核心功能以及它们在整合中的作用。 1. Struts2:Struts2是一个基于MVC(Model-View...

    spring mvc项目后端源码

    3. **Model-View-Controller(MVC)架构**:Spring MVC 遵循 MVC 设计模式,将业务逻辑(Model)、用户界面(View)和控制逻辑(Controller)分离,提高代码的可维护性和可测试性。 4. **Model**:模型对象持有业务...

    struts2+spring2+hibernate3 Annotation整合

    Struts2、Spring2和Hibernate3是Java Web开发中的三个重要框架,它们分别负责MVC模式中的Action层、业务逻辑层和服务数据访问层。将这三个框架整合在一起,可以实现高效、松耦合的Web应用程序。这里我们将深入探讨...

    spring mvc 学习指南

    XML配置是传统的配置方式,通过`&lt;mvc:annotation-driven&gt;`元素启用注解驱动,`&lt;bean&gt;`定义Controller等组件。而现在更推荐使用Java配置,通过@Configuration和@Bean注解实现更加灵活的配置。 路由(Mapping)是...

    spring mvc

    2. 引入必要的依赖库,如Spring、Spring MVC、Hibernate以及相关日志库的jar包。 3. 修改`web.xml`配置文件,配置DispatcherServlet作为前端控制器,并指定初始化参数`contextConfigLocation`,指明Spring配置文件的...

    Spring MVC tutorial

    3. **MVC配置**:使用`&lt;mvc:annotation-driven&gt;`元素启用注解驱动,让Spring自动扫描@Controller注解的类。 4. **视图解析器**:配置ViewResolver,例如`InternalResourceViewResolver`,指定前缀和后缀。 5. **...

Global site tag (gtag.js) - Google Analytics