【Spring实战-2】Spring4.0.4整合Hibernate4.3.6
下面是整个项目的截图;
配置文件分类存放
使用的jar包主要如下所示
前端界面分类存放,这里仅列举了jsp文件夹,如何需要引入其他js文件,如easyui、jquery等,可以在创建具体的分类文件夹;
- spring上下文文件(applicationContext-*.xml)加载路径;
- spring容器的监听器;
- 配置spring MVC;
<?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">
<!-- 从类路径下加载Spring配置文件,classpath关键字特指从类路径下加载 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/spring-config/applicationContext-*.xml</param-value>
</context-param>
<!-- 负责启动Spring容器的监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 配置Spring MVC -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/config/spring-config/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
对应文件:applicationContext-datasource-mysql.xml和database.properties;
#数据库相关配置
#hibernate.connection.url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:dbname
jdbc.connection.url=jdbc:mysql://localhost:3306/sampledb
#jdbc.connection.driver_class=oracle.jdbc.driver.OracleDriver
jdbc.connection.driver_class=com.mysql.jdbc.Driver
jdbc.connection.username=root
jdbc.connection.password=qaz
#Hibernate相关配置
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2dll.auto=update
hibernate.show_sql=true
数据源的配置,数据源的配置方式有多种,常见的是使用C3P0连接池,也可以使用BasicDataSource数据源;
- 制定database.properties文件的存放位置;
- 配置C3P0数据源;
- 为数据配置事务管理;
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--方式1:指定配置文件存放位置 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/config/database.properties</value>
</list>
</property>
</bean>
<!--方式2:指定配置文件存放位置 -->
<!-- <context:property-placeholder location="classpath:/config/database.properties" />
-->
<!-- 方式1:配置数据源,采用c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.connection.driver_class}" />
<property name="jdbcUrl" value="${jdbc.connection.url}" />
<property name="user" value="${jdbc.connection.username}" />
<property name="password" value="${jdbc.connection.password}" />
<property name="minPoolSize" value="2" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="1800" />
<property name="acquireIncrement" value="2" />
<property name="maxStatements" value="0" />
<property name="initialPoolSize" value="3" />
<property name="idleConnectionTestPeriod" value="1800" />
<property name="acquireRetryAttempts" value="4" />
<property name="breakAfterAcquireFailure" value="false" />
<property name="testConnectionOnCheckout" value="false" />
</bean>
<!-- 方式2:配置数据源,采用BasicDataSource数据源 -->
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${hibernate.connection.driver_class}"
p:url="${hibernate.connection.url}" p:username="${hibernate.connection.username}"
p:password="${hibernate.connection.password}" /> -->
<!-- jdbc事务管理器 -->
<bean id="txManagerJDBC"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<!--事务模板 -->
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager">
<ref local="txManagerJDBC" />
</property>
</bean>
</beans>
对应文件:applicationContext-hibernate-mysql.xml;
- 数据源配置;
- Hibernate属性配置;
- 关联orm映射文件;
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2dll.auto">${hibernate.hbm2dll.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<!-- 配置实体类 即相当于配置了 映射文件 -->
<!-- <property name="annotatedClasses"> <list> <value>com.ll.spring.orm.Cat</value>
</list> </property> -->
<!-- ORM映射文件存储位置 -->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:/config/hibernate-config</value>
</list>
</property>
</bean>
<!-- 配置Hibernate事务管理器 -->
<bean id="txManager_Hibernate"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager_Hibernate"/>
<!-- 配置事务异常封装 -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->
<tx:advice id="txAdvice" transaction-manager="txManager_Hibernate">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="read*" read-only="true" />
<tx:method name="list*" read-only="true" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- aop配置 -->
<aop:config >
<aop:pointcut id="txPointcut" expression="execution(* com.ll.service..*.*(..))" />
<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice" />
</aop:config>
</beans>
对应文件:springmvc-servlet.xml;
- 扫描组件的配置,扫描控制层所有标注@Controller的类;
- 配置视图解析器;
<?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:p="http://www.springframework.org/schema/p"
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">
<!-- 扫描web包,应用Spring的注解 -->
<context:component-scan base-package="com.ll.web" />
<!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/jsp/"
p:suffix=".jsp" />
</beans>
对应文件:applicationContext-Login.xml;
- 扫描组件的配置,扫描业务层、持久层分别标注了@Service 和
@Repository的类;
- 配置
HibernateTemplate和JdbcTemplate;
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.ll.dao" />
<context:component-scan base-package="com.ll.service" />
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"
p:sessionFactory-ref="sessionFactory" />
<!-- 配置Jdbc模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
</beans>
对应文件:User.hbm.xml和User.java;
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ll.domain.User" table="t_user">
<id name="userId" type="java.lang.Integer">
<column name="user_id" />
<generator class="increment" />
</id>
<property name="userName" type="java.lang.String">
<column name="user_name" length="60"/>
</property>
<property name="password" type="java.lang.String">
<column name="password" length="60"/>
</property>
<property name="credits" type="java.lang.Integer">
<column name="credits"/>
</property>
<property name="lastIp" type="java.lang.String">
<column name="last_ip" length="32" />
</property>
<property name="lastVisit" type="java.util.Date">
<column name="last_visit" length="23" />
</property>
</class>
</hibernate-mapping>
package com.ll.domain;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
public class User implements Serializable {
private int userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit;
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
public Date getLastVisit() {
return lastVisit;
}
public void setLastVisit(Date lastVisit) {
this.lastVisit = lastVisit;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
}
DROP DATABASE IF EXISTS sampledb;
CREATE DATABASE sampledb DEFAULT CHARACTER SET utf8;
USE sampledb;
##创建用户表
CREATE TABLE t_user (
user_id INT AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(30),
credits INT,
password VARCHAR(32),
last_visit datetime,
last_ip VARCHAR(23)
)ENGINE=InnoDB;
##创建用户登录日志表
CREATE TABLE t_login_log (
login_log_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
ip VARCHAR(23),
login_datetime datetime
)ENGINE=InnoDB;
##插入初始化数据
INSERT INTO t_user (user_name,password)
VALUES('admin','123456');
COMMIT;
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>论坛登录</title>
</head>
<body>
<c:if test="${!empty error}">
<font color="red"><c:out value="${error}" /></font>
</c:if>
<form action="<c:url value="test.action"/>" method="post">
用户名:
<input type="text" name="userName">
<br>
密 码:
<input type="password" name="password">
<br>
<input type="submit" value="登录" />
<input type="reset" value="重置" />
</form>
</body>
</html>
点击登录按键,就会跳转到:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>宝宝淘论坛</title>
</head>
<body>
${user.userName},欢迎您进入宝宝淘论坛,您当前积分为${user.credits};
</body>
</html>
控制层:
1. 报错信息:
所以我们需要在spring配置文件中加上对事物的控制的配置:
LoginController.java
package com.ll.web;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ll.domain.User;
import com.ll.service.IUserService;
import com.ll.service.UserService;
@Controller
public class LoginController {
@Autowired
private IUserService userService;
@RequestMapping(value = "/index.action")
public String loginPage() {
return "login";
}
@RequestMapping(value = "/test.action")
public String test(HttpServletRequest request, LoginCommand loginCommand) {
System.out.println("用户名:" + loginCommand.getUserName() + "--密码:"
+ loginCommand.getPassword());
User user = new User();
user.setUserName(loginCommand.getUserName());
user.setPassword(loginCommand.getPassword());
userService.save(user);
request.getSession().setAttribute("user", user);
return "main";
}
}
package com.ll.web;
public class LoginCommand {
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
package com.ll.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ll.dao.IUserDao;
import com.ll.dao.UserDao;
import com.ll.domain.User;
@Service
public class UserService implements IUserService{
@Autowired
private IUserDao userDao;
public void save(User user){
userDao.save(user);
}
}
package com.ll.service;
import com.ll.domain.User;
public interface IUserService {
public void save(User user);
}
package com.ll.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.ll.domain.User;
@Repository
public class UserDao implements IUserDao{
@Autowired
private HibernateTemplate hibernateTemplate;
@Autowired
private JdbcTemplate jdbcTemplate;
public void save(User user) {
// 测试jdbcTemplate操作
String sqlStr = " SELECT count(*) FROM t_user ";
int count = jdbcTemplate.queryForInt(sqlStr);
System.out.println("jdbcTemplate-用户个数:" + count);
//测试hibernateTemplate读写操作
try {
System.out.println("hibernateTemplate-用户个数: " + hibernateTemplate.find("from User").size());
hibernateTemplate.save(user);
} catch (Exception e) {
System.out.println("==》Hibernate保存数据错误...");
System.out.println(e.getMessage());
}
}
}
package com.ll.dao;
import com.ll.domain.User;
public interface IUserDao {
public void save(User user);
}
package com.ll.domain;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
public class User implements Serializable {
private int userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit;
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
public Date getLastVisit() {
return lastVisit;
}
public void setLastVisit(Date lastVisit) {
this.lastVisit = lastVisit;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
}
附件列表
【Spring实战-2】Spring4.0.4整合Hibernate4.3.6的更多相关文章
- Spring boot 2.1.0 -- swagger2 整合
依赖版本信息 Spring boot 2.1.0.RELEASE swagger2 2.7.0 1. mvn 配置 pom.xml 包引入 <!--swagger2依赖--> <d ...
- 基于restful注解(spring4.0.2整合flex+blazeds+spring-mvc)<一>
摘自: http://www.blogjava.net/liuguly/archive/2014/03/10/410824.html 参考官网:1.http://livedocs.adobe.com/ ...
- Spring Boot:Boot2.0版本整合Neo4j
前面介绍了Boot 1.5版本集成Neo4j,Boot 2.0以上版本Neo4j变化较大. 场景还是电影人员关系 Boot 2.0主要变化 GraphRepository在Boot2.0下不支持了,调 ...
- 【Spring实战-3】Spring整合Hibernate、Struts
作者:ssslinppp 1. 摘要 版本: Spring4.0.4:Hibernate4.3.5:struts2.3.16: 主要介绍了如下内容: 项目结构的规划: Spring下整合Hi ...
- (六)Spring4 整合Hibernate4,Struts2
第一节:S2SH 整合所需Jar 包 Struts2.3.16,Spring4.0.6,Hibernate4.3.5 整合所需jar 包: Struts2.3.16 jar 包 Spring4.0.6 ...
- 【Spring实战】----开篇(包含系列目录链接)
[Spring实战]----开篇(包含系列目录链接) 置顶2016年11月10日 11:12:56 阅读数:3617 终于还是要对Spring进行解剖,接下来Spring实战篇系列会以应用了Sprin ...
- [转]Struts2.3.16.1+Hibernate4.3.4+Spring4.0.2 框架整合
原文地址:http://blog.csdn.net/ycb1689/article/details/22928519 最新版Struts2+Hibernate+Spring整合 目前为止三大框架最新版 ...
- 【j2ee spring】27、巴巴荆楚网-整合hibernate4+spring4(2)
巴巴荆楚网-整合hibernate4+spring4(2) 1.图文项目 2.首先我们引入对应的jar包 这里用的是oracle 11g,所以我们使用的数据库连接jar包是ojdbc6, 的区别就是支 ...
- [CXF REST标准实战系列] 二、Spring4.0 整合 CXF3.0,实现测试接口(转)
转自:[CXF REST标准实战系列] 二.Spring4.0 整合 CXF3.0,实现测试接口 文章Points: 1.介绍RESTful架构风格 2.Spring配置CXF 3.三层初设计,实现W ...
随机推荐
- Active MQ的初步探索
参考链接: http://blog.csdn.net/jiuqiyuliang/article/details/46701559 JMS是jee规范,active MQ是该规范的实现 Active M ...
- Java——线程同步
body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...
- (C/C++学习笔记) 十七. 面向对象程序设计
十七. 面向对象程序设计 ● 面向对象程序设计的基本概念 ※ 类实际上是一种复杂的数据类型,它不仅包含不同类型的数据,还包含对这些数据的一些必要的操作. 而对象则是这种复杂的数据类型的一个变量. 类是 ...
- L209
China's Chang'e-4 probe entered a planned orbit Sunday morning // to prepare for the first-ever soft ...
- 技术揭秘“QQ空间”自动转发不良信息
大家经常会看到QQ空间自动转发一些附带链接的不良信息,即便我们的QQ密码并没有被盗取.最近通过对一个QQ空间自动转发链接进行分析,发现该自动转发机制通过利用腾讯网站存在漏洞的页面,精心构造出利用代码获 ...
- GitHub上最流行的Top 10 JavaScript项目
统计出Github中所有项目的数量,几乎是不可能的,而明确指出哪些是最优秀的项目就更不可能了.如果说到JavaScript,曾经极富创新的项目(很可能)在一两个月后就会变得过时.落后.以防被淹没在大量 ...
- Redis缓存系统-Java-Jedis操作Redis,基本操作以及 实现对象保存
源代码下载: http://download.csdn.net/detail/jiangtao_st/7623113 1.Maven配置 <dependency> <groupI ...
- STM32 LSM6DSL 陀螺仪数据采集
/************************************************************************************ * STM32 LSM6DS ...
- Gym - 101550A Artwork (并查集在线做法)
题目链接 题意:给你一个n*m的网格图,初始时格点全白,每次可以将一段连续的格点涂黑.求出每次操作之后白色连通块的数量. 看了看网上的题解,基本全是离线的做法.其实这道题是有在线的做法的,利用了对偶图 ...
- LG2521 [HAOI2011]防线修建
题意 题目描述 近来A国和B国的矛盾激化,为了预防不测,A国准备修建一条长长的防线,当然修建防线的话,肯定要把需要保护的城市修在防线内部了.可是A国上层现在还犹豫不决,到底该把哪些城市作为保护对象呢? ...