Spring3.x 整合hibernate 实现数据保存

最近跟一个项目,使用SpringSource Tool Suite 实现了一部分功能,但是由于是跟的别人的,所以对功能的实现原理不是很明确,特自己从头弄了一次,稍微明白了点

其实STS是使用的Spring3.x整合了hibernate。

以下为实现数据存储的功能详解:

1、所需工具---STS、MySQL、TomCat7.0

2、步骤-----

     1)新建一个工程项目---New->Dynamic Web Project 名称定义为:aiqservice

     2)进行各种配置工作

首先是web.xml配置

<?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">
  <display-name>aiqservice</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/cfg/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>aiqservice</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/cfg/mvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>aiqservice</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>
</web-app>
其中mvc-config.xml内容如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	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     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- spring内置支持的json转换 -->
	<mvc:annotation-driven />

	<!-- The controllers are autodetected POJOs labeled with the @Controller 
		annotation. -->
	<context:component-scan base-package="com.web.aiq" use-default-filters="false">
		<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation" />
	</context:component-scan>
	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources -->
	

	<mvc:resources mapping="/js/**" location="/js/" />
	<mvc:resources mapping="/css/**" location="/css/" />
	<mvc:resources mapping="/images/**" location="/images/" />

	<!-- Allows for mapping the DispatcherServlet to "/" by forwarding static 
		resource requests to the container's default Servlet -->
	<mvc:default-servlet-handler />

	<!-- Resolves localized messages*.properties and application.properties 
		files in the application to allow for internationalization. The messages*.properties 
		files translate Roo generated messages which are part of the admin interface, 
		the application.properties resource bundle localizes all application specific 
		messages such as entity names and menu items. -->
	<!-- <bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" 
		id="messageSource" p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application" 
		p:fallbackToSystemLocale="false"/> -->

	<!-- store preferred language configuration in a cookie -->
	<!-- <bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" 
		id="localeResolver" p:cookieName="locale"/> -->

	<!-- resolves localized <theme_name>.properties files in the classpath to 
		allow for theme support -->
	<!-- <bean class="org.springframework.ui.context.support.ResourceBundleThemeSource" 
		id="themeSource"/> -->

	<!-- store preferred theme configuration in a cookie -->
	<!-- <bean class="org.springframework.web.servlet.theme.CookieThemeResolver" 
		id="themeResolver" p:cookieName="theme" p:defaultThemeName="standard"/> -->

	<!-- This bean resolves specific types of exceptions to corresponding logical 
		- view names for error views. The default behaviour of DispatcherServlet 
		- is to propagate all exceptions to the servlet container: this will happen 
		- here with all other types of exceptions. -->
	<!-- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" 
		p:defaultErrorView="uncaughtException"> <property name="exceptionMappings"> 
		<props> <prop key=".DataAccessException">dataAccessFailure</prop> <prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop> 
		<prop key=".TypeMismatchException">resourceNotFound</prop> <prop key=".MissingServletRequestParameterException">resourceNotFound</prop> 
		</props> </property> </bean> -->
	<!-- <mvc:view-controller path="/login" view-name="login" /> -->
	
	<!-- allows for integration of file upload functionality -->
	<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver" />

	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jspx" />
	</bean>

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
		<property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" 
		value=".jspx" /> </bean> -->

	<!-- json view, capable of converting any POJO to json format -->
	<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</beans>
applicationContext的内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host" value="smtp.163.com" />  
        <property name="port" value="25" />  
        <property name="username" value="yuzhibojojo" />  
        <property name="password" value="5661215" />  
        <property name="defaultEncoding" value="utf-8" />  
        <property name="javaMailProperties">  
            <props>  
                <prop key="mail.smtp.auth">true</prop>  
            </props>  
        </property>  
	</bean>
	
	<bean id="emailService" class="com.web.aiq.SendOrderConfirmationEmailAdvice">
		<property name="mailSender" ref="mailSender" /> 
	</bean>
	
	<tx:annotation-driven transaction-manager="txManager" />
	
	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="shsSessionFactory" />
	</bean>
	
	<bean id="shsDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/aiqtest"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="initialSize" value="5"/>    
        <property name="maxActive" value="20"/>       
        <property name="maxIdle" value="5"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
        <property name="testWhileIdle" value="true"/>
        <property name="timeBetweenEvictionRunsMillis" value="1800000"/>
        <property name="numTestsPerEvictionRun" value="3"/>
        <property name="minEvictableIdleTimeMillis" value="1800000"/>
        <property name="validationQuery" value="SELECT 1"/>
    </bean>
    
    <bean id="shsSessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref local="shsDataSource" />
		</property>
		<property name="hibernateProperties">
			<ref bean="hibernateProperties" />
		</property>
		<!-- Must references all OR mapping files. -->
		<property name="mappingLocations">
			<list>
				<value>classpath:/com/web/aiq/hib/*.hbm.xml</value>
			</list>
		</property>
	</bean>
	<bean id="hibernateProperties"
		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="properties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">none</prop>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.query.substitutions">true 'T', false 'F'</prop>
				<prop key="hibernate.show_sql">false</prop>
				<prop key="hibernate.connection.autocommit">false</prop>
			</props>
		</property>
	</bean>
	
	<bean id="studentDAO" class="com.web.aiq.dao.StudentDAOImpl">
		<property name="sessionFactory">
			<ref local="shsSessionFactory" />
		</property>
	</bean>
    
</beans>
上面画 红线部分是用于实现发送邮件功能,可忽略

        3)进行代码的编写工作

            1、编写Student类      

package com.web.aiq.hib;

import java.util.Date;

public class Student {

	private long id;
	private String name;
	private int age;  
    private boolean gender;  
    private Date birthday;  
    private double score;
    
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isGender() {
		return gender;
	}
	public void setGender(boolean gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	} 
    
	@Override  
    public String toString(){  
        return "id=" + id + ",name=" + name + ",gender=" + gender + ",age=" + age  
        + ",birthday=" + this.birthday + ",score=" + score;  
    } 
    
    
}
               2、编写Student.hbm.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  
<hibernate-mapping>  
    <class name="com.web.aiq.hib.Student" table="student" catalog="aiqtest">  
        <id name="id" type="java.lang.Long">  
        	<column name="id"></column>
            <generator class="native"/>  
        </id>  
        <property name="name" type="string" >
            <column name="name" length="10" not-null="true" />
        </property>
        
        <property name="age" type="java.lang.Integer" >
            <column name ="age" not-null="true" />
        </property>
        
        <property name="gender" type="java.lang.Boolean">
        </property>
        <property name="birthday" type="date"/>  
        <property name="score" type="double"/>  
    </class>  
</hibernate-mapping>


Student.hbm.xml 文件要配置到applicationContext.xml中(文件中画 绿线部分)

                3、编写类StudentDAOImpl

package com.web.aiq.dao;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.web.aiq.hib.Student;


public class StudentDAOImpl implements StudentDAO{
	private static final Logger log = Logger.getLogger(StudentDAOImpl.class);

    private SessionFactory sessionFactory = null;
    
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    protected SessionFactory getSessionFactory() {
    	return sessionFactory;
    }
    
    @Transactional
    public void attachDirty(Student instance) {
        log.debug("attaching dirty Student instance");
        try {
            sessionFactory.getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        }
        catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
}
                4、编写接口StudentDAO

package com.web.aiq.dao;

import com.web.aiq.hib.Student;

public interface StudentDAO {
	public void attachDirty(Student instance);
}
需要将StudentImpl的对象部署到applicationContext.xml中如图中 黄线部分所示

           4)代码测试:

import java.util.Date;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.web.aiq.dao.StudentDAO;
import com.web.aiq.hib.Student;





@Controller
public class ViewController implements ApplicationContextAware{
	
	@Autowired
	private StudentDAO studentDAO;
	private ApplicationContext appContext;
	
	
	public void setApplicationContext(ApplicationContext appContext)
			throws BeansException {
		this.appContext = appContext;
	}
	
	@RequestMapping("/")
	public ModelAndView index(){
		Student student = new Student();
		student.setAge(20);
		student.setBirthday(new Date());
		student.setGender(false);
		student.setName("张三 ");
		student.setScore(98.6);
		try{
			studentDAO.attachDirty(student);
		}catch(Exception e){
			e.printStackTrace();
		}
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/index");
		return mv;
	}
可以发现已经将内容存入数据库中了---数据库库名--aiqtest---表名:student

库和表都是自己建立

下一次用sql添加的方式实验下,欢迎高手来踩,我记得很多文件时自己生成的,但是不知道怎么弄,欢迎指导

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值