由于对hibernate不是很熟悉,所以在搭建时也颇费周折,
特别是在引入第三发包和关系映射的时候,下面就对其做详细说明
说明:引入hibernate框架同样是使用注解进行开发!因为这样相对于配置映射文件,更为高效和方面!
1、引入Hibernate需要的相关包
2、新增spring-hibernate.xml(自定义名称,不一定完全一样),把连接和事物都交给spring管理
1)、spring-hibernate.xml配置文件
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${dburl}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
</bean>
<!-- 配置hibernate SessionFactory-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hiberante.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<!--加载映射类的位置, 可以加多个包 -->
<value>com.iobs.manager</value>
</list>
</property>
</bean>
<!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置事务异常封装 -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
2)、把数据库的参数放到配置文件application.properties
driverClassName=com.mysql.jdbc.Driver
dburl=jdbc:mysql://10.20.18.195:3306/iobs_manager?useUnicode=true&characterEncoding=utf8
user=root
password=123456
标红部分是指定字符集为utf-8
3)、在web.xml中新增要映入的xml文件,标红部分
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/web-context.xml,
/WEB-INF/spring-hibernate.xml
</param-value>
</context-param>
3、如果我们要用hibernate注解的,还需要在spring的配置web-context.xml文件中加入,
事物注解的自动装配配置,同时新增加载配置文件。
<context:property-placeholder location="classpath*:application.properties" />
<tx:annotation-driven transaction-manager="transactionManager"/>
加入<tx:>标签可能出错,需要在beans中加入xsd
<beans
..............
xmlns:tx="http://www.springframework.org/schema/tx"
........................
xsi:schemaLocation="http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
做完上传工作spring管理hibernate的工作就做完了,下面就是把前面的struts一起串联起来
4、把开始建的User类,通过注解映射到hibernate中
@Entity
@Table(name="iobs_info")
public class User {
@Id
private int id;
@Column(name="comp_name")
private String name;
@Column(name="join_date")
private Date date;
//getter、setter方法省略,自行新增
}
注解说明:
Entity说明该类为一个实体
Table对应到数据库的table名称
Id为主键
Column表的行,name属性为具体表行名称
5、新增BaseDao,BaseServer,UserServerImpl三个类,具体如下:
package com.iobs.manager.dao;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
@Component("baseDao")
public class BaseDao<T> {
@Resource
private SessionFactory sessionFactory;
public void saveObject(T t) {
sessionFactory.getCurrentSession().save(t);
};
}
注解解释:Component实例化BaseDao;Resource加载Spring管理SessionFactory
@Component("baseDao")
public class BaseDao<T> {
@Resource
private SessionFactory sessionFactory;
public void saveObject(T t) {
sessionFactory.getCurrentSession().save(t);
};
@SuppressWarnings("unchecked")
public List<T> getAll(Class<T> clazz) {
return sessionFactory.getCurrentSession().createQuery("from " +clazz.getName())
.list();
}
}
注解解释:Transcational指定该类添加到事物
package com.iobs.manager.server.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.iobs.manager.dao.BaseDao;
import com.iobs.manager.entity.User;
import com.iobs.manager.server.BaseServer;
@Service("userServerImpl")
public class UserServerImpl implements BaseServer<User>{
@Resource
private BaseDao<User> baseDao;
@Override
public void save(User user) {
baseDao.saveObject(user);
}
@SuppressWarnings("unchecked")
@Override
public List<User> getAll(User user) {
return baseDao.getAll((Class<User>) user.getClass());
}
}
注解解释:server实例化该类;
6、这样只要在UserAction类中,装配BaseServer的实现userServerImpl就可以实现数据持久化了。
//getter、setter方法省略,自行新增
package com.iobs.manager.action;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.iobs.manager.entity.User;
import com.iobs.manager.server.BaseServer;
@Controller("user")
public class UserAction {
@Autowired
public BaseServer<User> userServerImpl;
private User user;
private List<User> userList;
public String saveAndView(){
if (user != null) {
userServerImpl.save(user);
}
setUserList(userServerImpl.getAll(new User()));
user = null;
return "success";
}
//getter、setter方法省略,自行新增
}
注解解释:Contorller实例化UserAction;AutoWired自动装配BaseServer实现类,调用实现调用查询方法,放回一个List。
新增jsp页面user_saveAndView.jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath }"></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<h1>csp-iobs-manager</h1>
${path }
<!-- 遍历后台返回的userList-->
<c:forEach items="${userList}" var="user">
<li>${user.id} ${user.name}</li>
</c:forEach>
<form action="${path}/user_saveAndView" method="post">
<input name="user.name" type="text" width="200" />
<input type="submit" value="新增">
</form>
</body>
</html>
7、访问user_saveAndView
新增测试,新增“赵四”
浙公网安备 33010602011771号