整合所用版本:Spring3+Hibernate3+JDK1.7
导入Jar包
主要包括:Hibernate的注解jar包+自身jar包+Spring的jar包(其中orm是集成对象关系框架的jar)+数据库jar
Dao层
1.新建一个Dao的接口其中包含一个查询的方法(编写通用的dao )
package com.spring.dao;
import java.util.List;
public interface BaseDao {
List<?> findWithPage(int page,int rows,String HQL);
}
2.创建一个类实现该接口并继承HibernateDaoSupport类。集成后在编写数据操作的方法是,不在需要关心事务的操作,这写Spring已经帮我们完成了。
HibernateDaoSupport类由Spring提供的集成hibernate的一个抽象类,集成hibernate是这个,集成其它的是XXXDaoSupport。继承此类的作用:此类中有一个属性HibernateTemplate是spring提供的访问hibernate的模板类有增删改查方法。
package com.spring.dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class BaseDaoImp extends HibernateDaoSupport implements BaseDao{
//参数必须是final
@Override
public List<?> findWithPage(final int page, final int rows,final String HQL) {
//通过HibrenateCallback间接的获得session,session里面是原来hibernate的方法
return getHibernateTemplate().executeFind(new HibernateCallback<List<?>>() {
public List<?> doInHibernate(Session session) throws HibernateException, SQLException {
return session.createQuery(HQL).setFirstResult(page).setMaxResults(rows).list();
}
});
}
@Override
public void saveOrUpdateObj(Object obj) {
getHibernateTemplate().saveOrUpdate(obj);
//刷新缓存
getHibernateTemplate().flush();
//清空缓存
getHibernateTemplate().clear();
}
}
配置文件
主要包括:数据源的配置,hibernate自身配置信息、包扫描、JavaBean
数据源的配置:和MyBatis一样。
自身配置信息:MyBatis是Sqlseesionfactroy的配置,Hibernate中是sessionFactroy的配置,其对应的类注解时配Annao不是注解时配Local,主要包括Hibernate的方言,格式化显示sql语句,这些到放在标签中,它相当于map集合。
配置包扫描:标签中含有多个|标签:当不配扫描时,value是包里面的类一个一个的配进来,类写全名;当配扫描器时,只含一个value,值为实体类的包名。
配置自己的javaBean:配置hibernateTemplate,将sessionFactory引入。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="mydataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1/mydatabase" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="mydataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.spring.entity</value>
</list>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
实体类
此时hibernate的关系映射无法根据类创建表,因此类需要和数据库中内容一致,用的是注解方式,须将该类进行注解,注解为实体类。并书写每个书写的get和set方法。
package com.spring.entity;
import javax.persistence.*;
@Entity
public class Dept implements java.io.Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(length=40)
private String dname;
@Column(length=40)
private String dnumber;
@Column(length=40)
private String dloc;
}
service层:
1.接口
package com.spring.service;
import java.util.List;
import com.spring.entity.Dept;
public interface DeptService {
List<Dept>findDeptWithPage(int page,int rows);
}
2.实现类
package com.spring.service;
import java.util.List;
import com.spring.dao.BaseDao;
import com.spring.entity.Dept;
public class DeptServiceImp implements DeptService{
private BaseDao baseDao;
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
@SuppressWarnings("unchecked")
@Override
public List<Dept> findDeptWithPage(int page, int rows) {
return (List<Dept>) baseDao.findWithPage(page, rows, "from Dept");
}
}
3.配置javaBean
//dao层配置,注意他是继承了类,用parent属性进行配置
<bean id="baseDao" class="com.spring.dao.BaseDaoImp" parent="hibernateTemplate" />
<bean id="deptService" class="com.spring.service.DeptServiceImp">
<property name="baseDao" ref="baseDao" />
</bean>
控制器
package com.spring.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.spring.service.DeptService;
import com.spring.until.CommController;
@Controller
@RequestMapping("deptController")
public class DeptController extends CommController{
private DeptService deptService;
@RequestMapping("findDept")
public void findDept(HttpServletRequest request,HttpServletResponse response) throws IOException{
//getWebApplicationContext该方法在工具类中写了
deptService=(DeptService) getWebApplicationContext(request).getBean("deptService");
toJson(response, deptService.findDeptWithPage(0, 10));
}
}
工具类
package com.spring.until;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.google.gson.Gson;
public class CommController {
public WebApplicationContext getWebApplicationContext(HttpServletRequest request){
return WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
}
public void toJson(HttpServletResponse response,Object obj) throws IOException{
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
out.print(new Gson().toJson(obj));
out.flush();
out.close();
}
}
web.xml
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
//控制器的配置文件
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Spring-controller.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
页面
一个链接,点击可以显示数据库中的内容
<a href="<%=request.getContextPath()%>/deptController/findDept.action">测试spring整合Hibernate</a>