spring+hibernate有基于标签的,有基于xml配置的。现在一般来说都用基于标签的,xml的已经不流行了,但好不容易看到这里,还是记录下来,万一以后需要呢
1、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<!-- 这个是固定的,引入spring处理包 -->
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 这个是配置文件,可以写成一个,也可以分开写,这个是基于xml开发的 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/hib-config.xml,/WEB-INF/web-config.xml,/WEB-INF/service-config.xml,/WEB-INF/dao-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 这个是提交的时候,要用.do -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
2、hib-config.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<!-- 扫描包 -->
<context:component-scan base-package="com.sxt"/>
<!-- 支持aop注解 -->
<aop:aspectj-autoproxy />
<!-- 配置mysql数据库连接 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/myhib"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<!-- key的名字前面都要加hibernate. -->
<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>
<!-- 实体类配置 -->
<property name="packagesToScan">
<value>com.sxt.po</value>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--配置一个JdbcTemplate实例-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务管理 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<aop:config>
<!-- 实现类配置,这里没有写实现类 -->
<aop:pointcut expression="execution(public * com.sxt.service.impl.*.*(..))" id="businessService"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager" >
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
<!-- get开头的方法不需要在事务中运行 。
有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
<tx:method name="*"/> <!-- 其他方法在实务中运行 -->
</tx:attributes>
</tx:advice>
</beans>
3、dao-config.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 数据访问层配置 -->
<bean id="userDao" class="com.sxt.dao.UserDao">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
</beans>
4、service-config.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 业务逻辑层service配置 -->
<bean id="userService" class="com.sxt.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
5、web-confg.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Controller方法调用规则定义 -->
<bean id="paraMethodResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="action"/>
<property name="defaultMethodName" value="list"/>
</bean>
<!-- 页面View层基本信息设定 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<!--<property name="prefix" value="/myjsp/"/>-->
<property name="suffix" value=".jsp"/>
</bean>
<!-- servlet映射列表,所有控制层Controller的servlet在这里定义-->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="user.do">userController</prop> <!-- 控制器配置 -->
</props>
</property>
</bean>
<!-- 控制器配置指向具体的类 -->
<bean id="userController" class="com.sxt.action.UserController">
<property name="userService" ref="userService"></property>
</bean>
</beans>
6、UserController.java
package com.sxt.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.sxt.service.UserService;
public class UserController implements Controller {
private UserService userService;
public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse resp) throws Exception {
System.out.println("HelloController.handleRequest()");
//返回给页面的数据
req.setAttribute("a", "aaaa");
userService.add(req.getParameter("uname"));
return new ModelAndView("index");
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
7、UserDao.java
package com.sxt.dao;
import javax.annotation.Resource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import com.sxt.po.User;
public class UserDao {
private HibernateTemplate hibernateTemplate;
public void add(User u){
System.out.println("UserDao.add()");
hibernateTemplate.save(u);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
8、User.java
package com.sxt.po;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String uname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
}
package com.sxt.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.sxt.dao.UserDao;
import com.sxt.po.User;
public class UserService {
private UserDao userDao;
public void add(String uname){
System.out.println("UserService.add()");
User u = new User();
u.setUname(uname);
userDao.add(u);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
10、index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>${requestScope.a}</h1>
</body>
</html>
11、reg.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'reg.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action=user.do>
用户名:<input type=text name=uname /><br/>
<input type=hidden name=method value="reg"/>
<input type=submit value= 注册 />
</form>
</body>
</html>
数据库是mysql数据库,表名如下:
CREATE TABLE `user` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`uname` varchar(24) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
注意下面两个错误
org.hibernate.HibernateException: The database returned no natively generated identity value
数据库返回的没有本地生成的标识值的错误。
alter table t_news change
java.sql.SQLException: Field 'id' doesn't have a default value
ID的自增长没有加上去,加上就OK了
示例下载:http://download.csdn.net/detail/chexitianxia/9574046