SSH整合:将hibernate的配置交给Spring管理+Hibernate的模板的使用

SSH整合方式二:将hibernate的配置交给Spring管理(Struts2+Spring+Hibernate)

SSH方式:不带hibernate配置文件

一、创建web项目,引入jar和jsp页面

1、第一步:创建web项目,引入jar包

(1)Struts2的jar包:
  • jar包路径:struts-2.3.24-all\struts-2.3.24\apps\struts2-blank\WEB-INF\lib
    在这里插入图片描述
  • Struts2当中有一些包需要了解的:
    struts2-convention-plugin-2.3.24.jar -------Struts2的注解开发包。
    struts2-json-plugin-2.3.24.jar -----------------Struts2的整合AJAX的开发包
    struts2-spring-plugin-2.3.24.jar---------------Struts2和Spring整合的插件包
(2)Hibernate的jar包:
  • a、Hibernate的开发的必须的包:
  • jar包路径:hibernate-release-5.0.7.Final\lib\required
    在这里插入图片描述
  • b、hibernate和新版jdk可能有一些不兼容,引入4个兼容jar
    下载链接:https://download.csdn.net/download/qq_44757034/12440977
    在这里插入图片描述
  • c、引入mysql驱动
    -
  • d、日志记录jar:
    在这里插入图片描述
  • e、使用C3P0链接池
    jar路径:\hibernate-release-5.0.7.Final\hibernate-release-5.0.7.Final\lib\optional\c3p0
    在这里插入图片描述
  • f、注意:Struts2和Hibernate都引入了一个相同的jar包(javassist包)。需要删除一个
    在这里插入图片描述
    删除版本低的
(3)Spring的jar包:
  • IOC的开发:
    在这里插入图片描述
    引入Spring的日志文件
    在这里插入图片描述

  • AOP的开发:
    在这里插入图片描述

  • JDBC模板的开发:
    在这里插入图片描述

  • 只是做事务管理开发
    在这里插入图片描述

  • 整合web项目的开发:
    在这里插入图片描述

  • 整合单元测试的开发:
    在这里插入图片描述

  • 整合Hibernate的开发:

(4)全部的jar

在这里插入图片描述

2、第二步:引入配置文件

(1)Struts2的配置文件
  • web.xml
    web.xml当中配置核心过滤器
    在这里插入图片描述
  • struts.xml
    在src下创建struts.xml的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<!-- 配置Struts2的常量 -->
	<constant name="struts.action.extension" value="action" />
</struts>
(2)Spring的配置文件
  • web.xml
    在web.xml当中配置核心监听器,启动的时候加载Spring的配置文件,创建工厂,将工厂放入到ServletCont ext当中
    在这里插入图片描述
  • applicationContext.xml
    在src创建applicationContext.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: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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
  • 日志记录:
    在src下创建log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
# error warn info debug trace
log4j.rootLogger= info, stdout

3、第三步:创建包结构

在这里插入图片描述

4、第四步:创建相关的类

在这里插入图片描述

(1)创建实例对象Customer对象

在domain包下先创建

package com.itzheng.ssh.domain;

/*
 * 客户管理的实体类、
  CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话',
  `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
 */
public class Customer {
	private Long cust_id;
	private String cust_name;
	private String cust_source;
	private String cust_industry;
	private String cust_level;
	private String cust_phone;
	private String cust_mobile;
	public Long getCust_id() {
		return cust_id;
	}
	public void setCust_id(Long cust_id) {
		this.cust_id = cust_id;
	}
	public String getCust_name() {
		return cust_name;
	}
	public void setCust_name(String cust_name) {
		this.cust_name = cust_name;
	}
	public String getCust_source() {
		return cust_source;
	}
	public void setCust_source(String cust_source) {
		this.cust_source = cust_source;
	}
	public String getCust_industry() {
		return cust_industry;
	}
	public void setCust_industry(String cust_industry) {
		this.cust_industry = cust_industry;
	}
	public String getCust_level() {
		return cust_level;
	}
	public void setCust_level(String cust_level) {
		this.cust_level = cust_level;
	}
	public String getCust_phone() {
		return cust_phone;
	}
	public void setCust_phone(String cust_phone) {
		this.cust_phone = cust_phone;
	}
	public String getCust_mobile() {
		return cust_mobile;
	}
	public void setCust_mobile(String cust_mobile) {
		this.cust_mobile = cust_mobile;
	}
	public Customer() {
		// TODO Auto-generated constructor stub
	}
	public Customer(Long cust_id, String cust_name, String cust_source, String cust_industry, String cust_level,
			String cust_phone, String cust_mobile) {
		super();
		this.cust_id = cust_id;
		this.cust_name = cust_name;
		this.cust_source = cust_source;
		this.cust_industry = cust_industry;
		this.cust_level = cust_level;
		this.cust_phone = cust_phone;
		this.cust_mobile = cust_mobile;
	}
	@Override
	public String toString() {
		return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_source=" + cust_source
				+ ", cust_industry=" + cust_industry + ", cust_level=" + cust_level + ", cust_phone=" + cust_phone
				+ ", cust_mobile=" + cust_mobile + "]";
	}
}
(2)在web.action当中创建一个action
package com.itzheng.ssh.web.action;
import com.itzheng.ssh.domain.Customer;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/*
 * 客户管理的action的类
 */
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
	//模型驱动使用的对象	
	private Customer customer = new Customer();
	@Override
	public Customer getModel() {
		// TODO Auto-generated method stub
		return customer; 
	}
}
(3)创建CustomerService接口以及CustomerServiceImpl实现类(空的即可)
package com.itzheng.ssh.service;
/*
 * 客户管理的业务层的接口
 */
public interface CustomerService {
}
package com.itzheng.ssh.service.impl;
import com.itzheng.ssh.service.CustomerService;
public class CustomerServiceImpl implements CustomerService {
}
(4)创建CustomerDao接口以及CustomerDaoImpl实现类(空的即可)
package com.itzheng.ssh.dao;
/*
 * 客户管理DAO层的接口
 */
public interface CustomerDao {
}
package com.itzheng.ssh.dao.impl;
import com.itzheng.ssh.dao.CustomerDao;
/*
 * 客户管理的DAO层的实现类
 */
public class CustomerDaoUmpl implements CustomerDao {
}

5、第五步:引入相关的页面

这里引入的是提前写好的jsp页面
页面下载链接:https://download.csdn.net/download/qq_44757034/12615556
在这里插入图片描述

6、第六步:修改jsp页面

(1)修改menu.jsp

在这里插入图片描述
在这里插入图片描述

7、第七步:创建数据库

CREATE DATABASE ssh1;
use ssh1;
 CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话',
  `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

8、第八步:映射Customer文件Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!-- 建立类与表的映射 -->
	<class name="com.itzheng.ssh.domain.Customer"
		table="cst_customer">
		<!-- 建立类中的属性与表中的主键对应 -->
		<id name="cust_id" column="cust_id">
			<!-- 主键生成策略 -->
			<generator class="native" />
		</id>
		<!-- 建立类中的普通的属性和表的字段的对应映射 -->
		<property name="cust_name" column="cust_name" />
		<property name="cust_source" column="cust_source"/>
		<property name="cust_industry" column="cust_industry" />
		<property name="cust_level" column="cust_level" />
		<property name="cust_phone" column="cust_phone" />
		<property name="cust_mobile" column="cust_mobile" />
	</class>
</hibernate-mapping>

9、第九步:设置service实现类和dao实现类

package com.itzheng.ssh.service.impl;
import org.springframework.transaction.annotation.Transactional;
import com.itzheng.ssh.dao.CustomerDao;
import com.itzheng.ssh.domain.Customer;
import com.itzheng.ssh.service.CustomerService;
@Transactional
public class CustomerServiceImpl implements CustomerService {
	//注入DAO
	private CustomerDao customerDao;
	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}
	@Override
	public void save(Customer customer) {
		// TODO Auto-generated method stub
		System.out.println("Service当中的save方法执行了。"+customer);
		customerDao.save(customer);
	}
}
package com.itzheng.ssh.dao.impl;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.itzheng.ssh.dao.CustomerDao;
import com.itzheng.ssh.domain.Customer;
/*
 * 客户管理的DAO层的实现类
 */
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
	@Override
	public void save(Customer customer) {
		// TODO Auto-generated method stub
		System.out.println("Dao当中的save方法执行了");
		//保存customer对象
		this.getHibernateTemplate().save(customer);
	}
}

10、第十步:修改add.jsp页面,设置表单提交的action

在这里插入图片描述
设置对应input的内容
在这里插入图片描述

二、配置相关配置文件

1、在src下创建jdbc.properties文件

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssh1
jdbc.username=root
jdbc.password=root

2、在applicationContext.xml当配置

  • 配置C3P0数据库连接池
  • sessionFactory工厂,设置映射文件
  • 配置Action
  • 配置Service:将Service交给Spring管理
  • 配置DAO
  • 配置事务事务管理器
  • 开启注解事务
<?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: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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	<!-- 引入外部属性文件================================== -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	<!-- 配置C3P0链接池=================== -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 注入属性 -->
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="user" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- Spring整合Hibernate -->
	<!-- 引入Hibernate的配置信息=========================== -->
	<!-- sessionFactory工厂 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- 注入连接池 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 配置Hibernate的相关属性 -->
		<property name="hibernateProperties" >
		<!-- 注入复杂数据类型Properties -->
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		<!-- 设置映射文件 -->
		<property name="mappingResources">
			<list>
				<value>com/itzheng/ssh/domain/Customer.hbm.xml</value>
			</list>
		</property>
	</bean>
	<!-- 配置Action========================== -->
	<bean id="customerAction" class="com.itzheng.ssh.web.action.CustomerAction" scope="prototype">
		<property name="customerService" ref="customerService"></property>
	</bean>
	<!-- 配置Service==================== -->
	<!-- 将Service交给Spring管理 -->
	<bean id="customerService" class="com.itzheng.ssh.service.impl.CustomerServiceImpl">
		<!-- 将customerDao注入到CustomerServiceImpl的set方法当中 -->
		<property name="customerDao" ref="customerDao"></property>
	</bean>
	<!-- 配置DAO============================ -->
	<bean id="customerDao" class="com.itzheng.ssh.dao.impl.CustomerDaoImpl">
		<!-- 在Dao当中注入sessionFactory可以理解为数据库连接池 -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 配置事务事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<!-- 可以理解为在transactionManager事务管理器当中注入sessionFactory数据库连接池 -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 开启注解事务 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

将Hibernate的配置交给Spring

3、在struts.xml当配置action请求的跳转

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<!-- 配置Struts2的常量 -->
	<constant name="struts.action.extension" value="action" />
	<!-- 配置Action -->
	<package name="ssh1" extends="struts-default" namespace="/">
		<action name="customer_*" class="customerAction" method="{1}"></action>
	</package>
</struts>

4、创建Action类

package com.itzheng.ssh.web.action;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.itzheng.ssh.domain.Customer;
import com.itzheng.ssh.service.CustomerService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/*
 * 客户管理的action的类
 */
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
	//模型驱动使用的对象
	private Customer customer = new Customer();
	@Override
	public Customer getModel() {
		// TODO Auto-generated method stub
		return customer;
	}
	/*
	 * 注入CustomerService
	 */
	private CustomerService customerService;
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}
	/*
	 * 保存客户的方法:save
	 */
	public String save() {
		System.out.println("Action当中的save方法执行类。。。。。");
		customerService.save(customer);
		return NONE;
	}
}

5、测试

在这里插入图片描述
数据库
在这里插入图片描述

三、Hibernate的模板的使用

1、在dao以及daoImpl当中设置几个Hibernate常用的方法

  • 保存:save(Object obj);
  • 更新:update(Object obj)
  • 删除:delete(Oject obj)
  • 查询:
    查询一个
    get(Class c,Serializable id);
    load(Class c,Serializable id);
    查询多个:
    List<?> find(String hql,Object... args);
    List<?> findByCriteria(DetachedCriteria dc);
    List<?> findByCriteria(DetachedCriteria dc,int firstResult,int maxResults);分页
package com.itzheng.ssh.dao;
import java.util.List;
import com.itzheng.ssh.domain.Customer;
/*
 * 客户管理DAO层的接口
 */
public interface CustomerDao {
	void save(Customer customer);	
	void update(Customer customer);
	void delete(Customer customer);
	Customer findById(Long cust_id);
	List<Customer> findAllByHQL();
	List<Customer> findAllByQBC();
}
package com.itzheng.ssh.dao.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.itzheng.ssh.dao.CustomerDao;
import com.itzheng.ssh.domain.Customer;
/*
 * 客户管理的DAO层的实现类
 */
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
	@Override
	public void save(Customer customer) {
		// TODO Auto-generated method stub
		System.out.println("Dao当中的save方法执行了");
		// 保存customer对象
		this.getHibernateTemplate().save(customer);
	}
	// 修改操作
	@Override
	public void update(Customer customer) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(customer);
	}
	@Override
	public void delete(Customer customer) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().delete(customer);
	}
	@Override
	public Customer findById(Long cust_id) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(Customer.class, cust_id);
	}
	@Override
	public List<Customer> findAllByHQL() {
		// TODO Auto-generated method stub
		List<Customer> find = (List<Customer>) this.getHibernateTemplate().find("from Customer");
		return find;
	}
	@Override
	public List<Customer> findAllByQBC() {
		// TODO Auto-generated method stub
		DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
		List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria);
		return list;
	}
}

2、在service以及serviceImpl当中调用dao的方法

package com.itzheng.ssh.service;
import java.util.List;
import com.itzheng.ssh.domain.Customer;
/*
 * 客户管理的业务层的接口
 */
public interface CustomerService {
	void save(Customer customer);
	void update(Customer customer);
	void delete(Customer customer);
	void findById(Long cust_id);
	List<Customer> findAllByHQL();
	List<Customer> findAllByQBC();
}
package com.itzheng.ssh.service.impl;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.itzheng.ssh.dao.CustomerDao;
import com.itzheng.ssh.domain.Customer;
import com.itzheng.ssh.service.CustomerService;
@Transactional
public class CustomerServiceImpl implements CustomerService {
	//注入DAO
	private CustomerDao customerDao;
	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}
	@Override
	public void save(Customer customer) {
		// TODO Auto-generated method stub
		System.out.println("Service当中的save方法执行了。"+customer);
		customerDao.save(customer);
	}
	@Override
	public void update(Customer customer) {
		// TODO Auto-generated method stub
		customerDao.update(customer);
	}
	@Override
	public void delete(Customer customer) {
		// TODO Auto-generated method stub
		customerDao.delete(customer);
	}
	@Override
	public void findById(Long cust_id) {
		// TODO Auto-generated method stub
		customerDao.findById(cust_id);
	}
	@Override
	public List<Customer> findAllByHQL() {
		// TODO Auto-generated method stub
		return customerDao.findAllByHQL();
	}
	@Override
	public List<Customer> findAllByQBC() {
		// TODO Auto-generated method stub
		return customerDao.findAllByQBC();
	}
}

3、创建一个测试类

(1)修改
package com.itzheng.ssh.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.itzheng.ssh.domain.Customer;
import com.itzheng.ssh.service.CustomerService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SSHDemo1 {
	@Resource(name = "customerService")
	private CustomerService customerService;
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}
	@Test
	// 
	public void demo1() {
		Customer customer = customerService.findById(1l);
		customer.setCust_name("赵一");		
		customerService.update(customer);
		System.out.println(customer);
	}
}

在这里插入图片描述

(2)删除

在这里插入图片描述

(3)查询

在这里插入图片描述

(4)查询所有HQL

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(5)查询所有QBC

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44757034/article/details/107381775