环境准备:
1、创建Java web工程
2、创建数据库和表结构
/*创建客户表*/
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_address` varchar(128) DEFAULT NULL COMMENT '客户联系地址',
`cust_phone` varchar(64) DEFAULT NULL COMMENT '客户联系电话',
PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8;
/*创建联系人表*/
CREATE TABLE `cst_linkman` (
`lkm_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '联系人编号(主键)',
`lkm_name` varchar(16) DEFAULT NULL COMMENT '联系人姓名',
`lkm_gender` varchar(10) DEFAULT NULL COMMENT '联系人性别',
`lkm_phone` varchar(16) DEFAULT NULL COMMENT '联系人办公电话',
`lkm_mobile` varchar(16) DEFAULT NULL COMMENT '联系人手机',
`lkm_email` varchar(64) DEFAULT NULL COMMENT '联系人邮箱',
`lkm_position` varchar(16) DEFAULT NULL COMMENT '联系人职位',
`lkm_memo` varchar(512) DEFAULT NULL COMMENT '联系人备注',
PRIMARY KEY (`lkm_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
3、编写实体类
Customer.java
4、编写业务层接口
public interface ICustomerService {
//查询客户所有
List<Customer> findAllCustomer();
//保存客户
void saveCustomer(Customer customer);
}
及其实现类
public class ICustomerServiceImpl implements ICustomerService {
private ICustomerDao customerDao;
//注入dao
public void setCustomerDao(ICustomerDao customerDao) {
this.customerDao = customerDao;
}
@Override
public List<Customer> findAllCustomer() {
return customerDao.findAllCustomer();
}
@Override
public void saveCustomer(Customer customer) {
customerDao.saveCustomer(customer);
}
5、创建持久层接口
public interface ICustomerDao {
//查询所有客户
List<Customer> findAllCustomer();
//保存客户
void saveCustomer(Customer customer);
}
及其实现类
public class ICustomerDaoImpl implements ICustomerDao {
/*private SessionFactory factory;
public void setFactory(SessionFactory factory) {
this.factory = factory;
}
public Session getSession() {
return factory.getCurrentSession();
}//方法2
*/
// private Session session;//保证注入的session必须是当前线程的session 方法3
private HibernateTemplate hibernateTemplate; //方法4
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public List<Customer> findAllCustomer() {
System.out.println("搭建spring的ioc开发环境并测试");
return (List<Customer>) hibernateTemplate.find("from Customer"); //方法4
}
@Override
public void saveCustomer(Customer customer) {
// factory.getCurrentSession().save(customer); //原始方法1
// getSession().save(customer); //方法2
// session.save(customer); //方法3
hibernateTemplate.save(customer); //方法4
}
}
一、基于XML的独立式整合
1、jar包导入
2、hibernate映射文件
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 package="com.fzy.entity">
<class name="Customer" table="cst_customer">
<id name="custId" column="cust_id">
<generator class="native"></generator>
</id>
<property name="custName" column="cust_name"></property>
<property name="custSource" column="cust_source"></property>
<property name="custIndustry" column="cust_industry"></property>
<property name="custLevel" column="cust_level"></property>
<property name="custAddress" column="cust_address"></property>
<property name="custPhone" column="cust_phone"></property>
</class>
</hibernate-mapping>
3、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>spring01</display-name>
<!-- 配置spring提供的监听器,用于监听servletContext对象创建,同时为我们创建spring的容器
默认情况下:它只能加载位置是在WEB-INF目录中的spring配置文件,同时文件名称必须是applicationContext.xml
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 手动指定spring的配置文件位置,需要使用ServletContext的初始化参数 -->
<!-- <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring/applicationContext.xml</param-value>
</context-param> -->
<!-- 配置struts2和核心过滤器
严重:Exception starting filter struts2 Class: com.opensymphony.xwork2.spring.SpringObjectFactory
jar包冲突,虽然在运行环境的jar包中没有与spring关联的,但在lib包下有,删除即可
-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<!-- 手动指定struts2配置文件的位置:此处的配置绝大多数都是固定的
(打开会出现资源拦截的问题,原先能打开的页面会报错)
-->
<!-- <init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,config/struts/struts.xml</param-value>
</init-param> -->
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
4、hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 配置SessionFactory-->
<session-factory>
<!-- 第一部分:连接数据库的信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ssh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!-- 数据库的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 第二部分:hibernate的可选配置 -->
<!-- 是否显示hibernate生成的SQL语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 是否使用格式化输出sql语句到控制台 -->
<property name="hibernate.format_sql">false</property>
<!-- 配置hibernate采用何种方式生成DDL语句 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 设置hibernate的连接池提供商 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 把session和线程绑定,从而实现一个线程只有一个Session(hibernate单独使用) -->
<!-- <property name="hibernate.current_session_context_class">thread</property> -->
<!-- 与spring整合 -->
<property name="hibernate.current_session_context_class">
org.springframework.orm.hibernate5.SpringSessionContext
</property>
<!-- 第三部分:映射配置文件的位置 -->
<mapping resource="com/fzy/entity/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5、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>
<!-- 开启开发者模式 -->
<constant name="struts.devMode" value="true"></constant>
<!-- 配置动作 -->
<package name="customer" extends="struts-default" namespace="/customer">
<action name="addUICustomer" class="com.fzy.action.CustomerAction" method="addUICustomer">
<result name="addUICustomer">/jsp/customer/add.jsp</result>
</action>
<action name="findAllCustomer" class="com.fzy.action.CustomerAction" method="findAllCustomer">
<result name="findAllCustomer">/jsp/customer/list.jsp</result>
</action>
</package>
</struts>
6、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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置service -->
<bean id="customerService" class="com.fzy.service.impl.ICustomerServiceImpl">
<property name="customerDao" ref="customerDao"></property>
</bean>
<!-- 配置dao -->
<bean id="customerDao" class="com.fzy.dao.impl.ICustomerDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!-- 配置hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置sessionFactory:让spring接管sessionFactory的创建
用spring提供的一个SessionFactory:LocalSessionFactoryBean
创建SessionFactory有三部分必不可少的信息。三部分信息在hibernate主配置文件中都有。
把hibernate主配置文件的位置注入进来
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
<!-- 建立切入点表达式和事务通知的关联 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
7、jsp页面按钮action请求
8、CustomerAction.java:
package com.fzy.action;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.fzy.entity.Customer;
import com.fzy.service.ICustomerService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
* 客户的动作类
* @ClassName: CustomerAction
* @Description: TODO(这里用一句话描述这个类的作用)
* @author fzywhy
* @date 2018年9月26日
*
*/
public class CustomerAction extends ActionSupport implements
ModelDriven<Customer> {
private Customer customer = new Customer();
private List<Customer> customers;
private ICustomerService customerService;
public void setCustomerService(ICustomerService customerService) {
this.customerService = customerService;
}
@Override
public Customer getModel() {
return customer;
}
//此种方式根本不能用,因为由于动作类是多例的,每次都会创建新的容器,导致容器中的bean也会创建新的。
// public CustomerAction(){
// System.out.println("==================");
// ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// ICustomerService cs = (ICustomerService) ac.getBean("customerService");
// this.setCustomerService(cs);
// }
//此种方式解决了容器多例的问题,保证了容器一个应用只有一个,但是我们的代码边臃肿了,每个action都需要这么写一下。
// public CustomerAction(){
// ServletContext application = ServletActionContext.getServletContext();
// ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(application);
// System.out.println(ac);
// ICustomerService cs = (ICustomerService) ac.getBean("customerService");
// this.setCustomerService(cs);
// } //可用struts2-spring-pluginJAR包优化,自动创建
/*原因:
1、容器是单例的2、容器,一个应用应该只有一个,应该存起来,存到应用域里
3、应用的key可以在源码中找到(application setAttribute)
4、struts2的配置文件有加载顺序,遇到相同的配置,后加载的覆盖先加载的
5、这些代码的取用都是固定的。*/
//查询所有客户
public String findAllCustomer() {
customers = customerService.findAllCustomer();
return "findAllCustomer";
}
//获取添加客户页面
public String addUICustomer() {
return "addUICustomer";
}
//==========================================
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
9、项目目录截图
二、基于XML的引入式整合
所谓:引入式整合就是把hibernate.cfg.xml中的配置都写在spring的配置文件中
改为:
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 第一部分:连接数据库的 用连接池-->
<property name="dataSource" ref="dataSource"></property>
<!-- 第二部分:hibernate的可选配置 -->
<property name="hibernateProperties">
<props>
<prop key=""></prop>
<!-- 数据库的方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 是否显示hibernate生成的SQL语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否使用格式化输出sql语句到控制台 -->
<prop key="hibernate.format_sql">false</prop>
<!-- 配置hibernate采用何种方式生成DDL语句 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 把session和线程绑定,从而实现一个线程只有一个Session -->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!-- 第三部分:映射文件的位置
mappingResources:它是一个注入string数组类型的数据。提供的是映射文件的位置。有几个映射文件,就需要写几个。
mappingDirectoryLocations:它是注入一个Resource类型的数组。提供的是映射文件所在的目录。此属性一般多用于一个项目有多个地方存放映射配置。
//服务端
server_domain
//移动端
mobile_domain
mappingLocations:它是注入一个Resource类型的数组。提供的映射文件的位置。它可以使用通配符。
-->
<property name="mappingLocations">
<array>
<value>classpath:com/fzy/entity/*.hbm.xml</value>
</array>
</property>
</bean>
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
三、基于注解的整合
所谓:注解整合使用上面的环境,把xml文件的配置全部换位注解方式
spring的注解整合分为两种方式:xml文件和纯注解
hibernate注解整合是把实体类映射改为JPA注解映射
1、整合步骤:spring使用xml文件
(spring配置使用注解实现)
1、导入必备jar包
2、在spring配置文件中导入context名称空间及约束
<?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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
3、在spring配置文件中配置要扫描的包
<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="com.fzy"></context:component-scan>
4、注解配置action、service、dao
action:
@Controller("customerAction")
//取代struts.xml中的配置
@ParentPackage("struts-default")
@Namespace("/customer")
@Results({
@Result(name="addUICustomer",type="dispatcher",location="/jsp/customer/add.jsp"),
@Result(name="findAllCustomer",type="dispatcher",location="/jsp/customer/list.jsp"),
@Result(name="listCustomer",type="redirectAction",location="/findAllCustomer")
})
public class CustomerAction extends ActionSupport implements
ModelDriven<Customer> {
private Customer customer = new Customer();
private List<Customer> customers;
@Resource(name="customerService")
private ICustomerService customerService;
//可被注解取代@controller与@Resource
/*public void setCustomerService(ICustomerService customerService) {
this.customerService = customerService;
}*/
@Override
public Customer getModel() {
return customer;
}
//此种方式根本不能用,因为由于动作类是多例的,每次都会创建新的容器,导致容器中的bean也会创建新的。
// public CustomerAction(){
// System.out.println("==================");
// ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// ICustomerService cs = (ICustomerService) ac.getBean("customerService");
// this.setCustomerService(cs);
// }
//此种方式解决了容器多例的问题,保证了容器一个应用只有一个,但是我们的代码边臃肿了,每个action都需要这么写一下。
// public CustomerAction(){
// ServletContext application = ServletActionContext.getServletContext();
// ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(application);
// System.out.println(ac);
// ICustomerService cs = (ICustomerService) ac.getBean("customerService");
// this.setCustomerService(cs);
// } //可用struts2-spring-pluginJAR包优化,自动创建
/*原因:
1、容器是单例的2、容器,一个应用应该只有一个,应该存起来,存到应用域里
3、应用的key可以在源码中找到(application setAttribute)
4、struts2的配置文件有加载顺序,遇到相同的配置,后加载的覆盖先加载的
5、这些代码的取用都是固定的。*/
//保存添加用户
@Action("addCustomer")
public String addCustomer(){
customerService.saveCustomer(customer);
return "listCustomer";
}
//查询所有客户
@Action("findAllCustomer")
public String findAllCustomer() {
customers = customerService.findAllCustomer();
return "findAllCustomer";
}
//获取添加客户页面
@Action("addUICustomer")
public String addUICustomer() {
return "addUICustomer";
}
//==========================================
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
service:
@Service("customerService")
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public class ICustomerServiceImpl implements ICustomerService {
@Resource(name="customerDao")
private ICustomerDao customerDao;
//注入dao,被@Resource注解取代
/* public void setCustomerDao(ICustomerDao customerDao) {
this.customerDao = customerDao;
}*/
@Override
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public List<Customer> findAllCustomer() {
return customerDao.findAllCustomer();
}
@Override
public void saveCustomer(Customer customer) {
customerDao.saveCustomer(customer);
}
}
dao:
@Repository("customerDao")
public class ICustomerDaoImpl implements ICustomerDao {
/*private SessionFactory factory;
public void setFactory(SessionFactory factory) {
this.factory = factory;
}
public Session getSession() {
return factory.getCurrentSession();
}//方法2
*/
// private Session session;//保证注入的session必须是当前线程的session 方法3
@Resource(name="hibernateTemplate")
private HibernateTemplate hibernateTemplate; //方法4
//注入hibernateTemplate,被@Resource注解取代
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public List<Customer> findAllCustomer() {
System.out.println("搭建spring的ioc开发环境并测试");
return (List<Customer>) hibernateTemplate.find("from Customer"); //方法4
}
@Override
public void saveCustomer(Customer customer) {
// factory.getCurrentSession().save(customer); //原始方法1
// getSession().save(customer); //方法2
// session.save(customer); //方法3
hibernateTemplate.save(customer); //方法4
}
}
5、在spring配置文件中配置hibernateTemplate
<!-- 配置hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
6、在spring配置文件中配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
7、在spring配置文件中开启spring对注解事务的支持
!-- 开启spring对注解事务的支持
(serviceimpl中)用@Transactional取代
-->
<tx:annotation-driven transaction-manager="transactionManager"/>
8、在客户的业务层实现类上使用@Transactional注解
@Service("customerService")
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public class ICustomerServiceImpl implements ICustomerService {
@Resource(name="customerDao")
private ICustomerDao customerDao;
//注入dao,被@Resource注解取代
/* public void setCustomerDao(ICustomerDao customerDao) {
this.customerDao = customerDao;
}*/
@Override
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public List<Customer> findAllCustomer() {
return customerDao.findAllCustomer();
}
@Override
public void saveCustomer(Customer customer) {
customerDao.saveCustomer(customer);
}
}
2、hibernate映射使用注解配置实现
1、实体类映射注解配置
@Entity
@Table(name="cst_customer")
public class Customer implements Serializable {
@Id
@Column(name="cust_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long custId;
@Column(name="cust_name")
private String custName;
@Column(name="cust_source")
private String custSource;
@Column(name="cust_industry")
private String custIndustry;
@Column(name="cust_level")
private String custLevel;
@Column(name="cust_address")
private String custAddress;
@Column(name="cust_phone")
private String custPhone;
public Long getCustId() {
return custId;
}
public void setCustId(Long custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustSource() {
return custSource;
}
public void setCustSource(String custSource) {
this.custSource = custSource;
}
public String getCustIndustry() {
return custIndustry;
}
public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
public String getCustAddress() {
return custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
@Override
public String toString() {
return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource
+ ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
+ ", custPhone=" + custPhone + "]";
}
}
2、spring中SessionFactory配置修改
<!-- 配置sessionFactory:让spring接管sessionFactory的创建
用spring提供的一个SessionFactory:LocalSessionFactoryBean
创建SessionFactory有三部分必不可少的信息。三部分信息在hibernate主配置文件中都有。
把hibernate主配置文件的位置注入进来
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 第一部分:连接数据库的 用连接池-->
<property name="dataSource" ref="dataSource"></property>
<!-- 第二部分:hibernate的可选配置 -->
<property name="hibernateProperties">
<props>
<prop key=""></prop>
<!-- 数据库的方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 是否显示hibernate生成的SQL语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否使用格式化输出sql语句到控制台 -->
<prop key="hibernate.format_sql">false</prop>
<!-- 配置hibernate采用何种方式生成DDL语句 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 把session和线程绑定,从而实现一个线程只有一个Session -->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!-- 第三部分:映射文件的位置
mappingResources:它是一个注入string数组类型的数据。提供的是映射文件的位置。有几个映射文件,就需要写几个。
mappingDirectoryLocations:它是注入一个Resource类型的数组。提供的是映射文件所在的目录。此属性一般多用于一个项目有多个地方存放映射配置。
//服务端
server_domain
//移动端
mobile_domain
mappingLocations:它是注入一个Resource类型的数组。提供的映射文件的位置。它可以使用通配符。
-->
<!-- 指定实体类所在的包,当创建SessionFactory,会去该包中扫描实体类上的注解,从而生成映射配置 -->
<!—指定扫描映射注解的包-->
<property name="packagesToScan">
<array>
<value>com.fzy.entity</value>
</array>
</property>
</bean>
3、struts2配置使用注解实现
1、导入struts2注解的jar包
2、使用注解配置Action
两种方式:
@Controller("customerAction")
@Scope("prototype")
//-------以下都是struts2的注解-----------
@ParentPackage("struts-default")//指定当前包的父包
@Namespace("/customer")//指定名称空间,访问当前action的所有方法都需要有名称空间
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
private Customer customer = new Customer();
@Autowired
private ICustomerService customerService;
@Override
public Customer getModel() {
return customer;
}
private List<Customer> customers;
//用于配置动作名称
@Action(value="findAllCustomer",results={
@Result(name="findAllCustomer",
type="dispatcher",
location="/jsp/customer/list.jsp")
})
public String findAllCustomer(){
customers = customerService.findAllCustomer();
return "findAllCustomer";
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
@Controller("customerAction")
//取代struts.xml中的配置
@ParentPackage("struts-default")
@Namespace("/customer")
@Results({
@Result(name="addUICustomer",type="dispatcher",location="/jsp/customer/add.jsp"),
@Result(name="findAllCustomer",type="dispatcher",location="/jsp/customer/list.jsp"),
@Result(name="listCustomer",type="redirectAction",location="/findAllCustomer")
})
public class CustomerAction extends ActionSupport implements
ModelDriven<Customer> {
private Customer customer = new Customer();
private List<Customer> customers;
@Resource(name="customerService")
private ICustomerService customerService;
@Override
public Customer getModel() {
return customer;
}
//保存添加用户
@Action("addCustomer")
public String addCustomer(){
customerService.saveCustomer(customer);
return "listCustomer";
}
//查询所有客户
@Action("findAllCustomer")
public String findAllCustomer() {
customers = customerService.findAllCustomer();
return "findAllCustomer";
}
//获取添加客户页面
@Action("addUICustomer")
public String addUICustomer() {
return "addUICustomer";
}
//==========================================
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
整理:
//readme
ssh环境搭建
1、环境准备
1)、创建JavaWeb工程(2.5)导入所需jar包
2)、创建数据库和表结构(见readme/sql/customer-linkman.sql)
3)、创建工作包结构entity,dao,service,action
4)、编写实体类Customer.java,Linkman.java
5)、编写持久层接口CustomerDao.java(Interface)及其实现类CustomerDaoImpl.java
6)、编写业务层接口CustomerService.java(Interface)及其实现类CustomerServiceImpl.java
7)、编写Action,CustomerAction.java
一、基于xml的独立式整合
8)、编写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 package="com.fzy.entity">
<!-- 实体类与数据表结构映射 -->
<class name="Customer" table="cst_customer">
<!-- 自增长主键 -->
<id name="custId" column="cust_id">
<generator class="native"></generator>
</id>
<!-- 非主键字段 -->
<property name="custName" column="cust_name"></property>
<property name="custSource" column="cust_source"></property>
<property name="custIndustry" column="cust_industry"></property>
<property name="custLevel" column="cust_level"></property>
<property name="custAddress" column="cust_address"></property>
<property name="custPhone" column="cust_phone"></property>
</class>
</hibernate-mapping>
9)、编写web.xml(spring监听器,struts的核心控制器)
10)、编写hibernate核心配置文件hibernate.cfg.xml
(连接数据库的信息:driver_class,url,username,password,dialect
hibernate的可选配置:是否显示生成的sql语句
是否格式化输出sql语句到控制台
hibernate采用何种方式生成DDL语句
hibernate的连接池供应商
(session与线程的绑定,实现一个线程只有一个session)
与spring整合
映射文件的配置:映射配置文件的位置)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 配置SessionFactory-->
<session-factory>
<!-- 第一部分:连接数据库的信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ssh-1</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!-- 数据库的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 第二部分:hibernate的可选配置 -->
<!-- 是否显示hibernate生成的SQL语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 是否使用格式化输出sql语句到控制台 -->
<property name="hibernate.format_sql">false</property>
<!-- 配置hibernate采用何种方式生成DDL语句 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 设置hibernate的连接池提供商 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 把session和线程绑定,从而实现一个线程只有一个Session(hibernate单独使用) -->
<!-- <property name="hibernate.current_session_context_class">thread</property> -->
<!-- 与spring整合 -->
<property name="hibernate.current_session_context_class">
org.springframework.orm.hibernate5.SpringSessionContext
</property>
<!-- 第三部分:映射配置文件的位置 -->
<mapping resource="com/fzy/entity/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
11)、编写struts.xml(开启开发者模式,配置动作)
12)、编写application.xml
(配置service,配置dao,配置hibernateTemplate,配置sessionFactory
配置事务管理器,配置事务的通知,配置aop(配置切入点表达式,建立切入点表达式和事务通知的关联))
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置service -->
<bean id="customerService" class="com.fzy.service.impl.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"></property>
</bean>
<!-- 配置dao -->
<bean id="customerDao" class="com.fzy.dao.impl.CustomerDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!-- 配置hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置sessionFactory:让spring接管sessionFactory的创建
用spring提供的一个SessionFactory:LocalSessionFactoryBean
创建SessionFactory有三部分必不可少的信息。三部分信息在hibernate主配置文件中都有。
把hibernate主配置文件的位置注入进来
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.fzy.service.impl.*.*(..))" id="pt1"/>
<!-- 建立切入点表达式和事务通知的关联 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
13)、导入静态页面及布局
问题:导入伊始,会报JavaWeb:
报错信息The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
原来Javaweb工程类中没有添加Tomcat运行时相关类导致。
下面是具体的解决方法:
1、右击web工程-》属性或Build Path-》Java Build Path->Libraries-> Add Libray...->Server Runtime -》Tomcat Server
2、切换到Java Build Path界面中的Orader and Export,选择Tomcat。
注意:
按以上方法操作时,若打开Server Runtime后一片空白,需要设置Apache服务器。
设置方法为:window->Preferences->Server->Runtime Environment -> add --> 选择Apache的版本后点Next,再填入你apache服务器软件的安装(解压后)地址。
14)、出现问题,尚未完成,静待解决
二、基于XML的引入式整合
所谓:引入式整合就是把hibernate.cfg.xml中的配置都写在spring的配置文件中
<!-- 基于XML的独立式整合............................ -->
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
-->
<!-- .......................................... -->
<!-- 基于XML的引入式整合
所谓:引入式整合就是把hibernate.cfg.xml中的配置都写在spring的配置文件中
-->
<!-- start================================================ -->
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 第一部分:连接数据库的 用连接池-->
<property name="dataSource" ref="dataSource"></property>
<!-- 第二部分:hibernate的可选配置 -->
<property name="hibernateProperties">
<props>
<prop key=""></prop>
<!-- 数据库的方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 是否显示hibernate生成的SQL语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否使用格式化输出sql语句到控制台 -->
<prop key="hibernate.format_sql">false</prop>
<!-- 配置hibernate采用何种方式生成DDL语句 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 把session和线程绑定,从而实现一个线程只有一个Session -->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!-- 第三部分:映射文件的位置
mappingResources:它是一个注入string数组类型的数据。提供的是映射文件的位置。有几个映射文件,就需要写几个。
mappingDirectoryLocations:它是注入一个Resource类型的数组。提供的是映射文件所在的目录。此属性一般多用于一个项目有多个地方存放映射配置。
//服务端
server_domain
//移动端
mobile_domain
mappingLocations:它是注入一个Resource类型的数组。提供的映射文件的位置。它可以使用通配符。
-->
<property name="mappingLocations">
<array>
<value>classpath:com/fzy/entity/*.hbm.xml</value>
</array>
</property>
</bean>
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- end===================================================== -->
三、基于注解的整合
所谓:注解整合使用上面的环境,把xml文件的配置全部换位注解方式
spring的注解整合分为两种方式:xml文件和纯注解
hibernate注解整合是把实体类映射改为JPA注解映射
1、整合步骤:spring使用xml文件
(spring配置使用注解实现)
1、导入必备jar包
2、在spring配置文件中导入context名称空间及约束
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
3、在spring配置文件中配置要扫描的包
<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="com.fzy"></context:component-scan>
4、注解配置action、service、dao
5、在spring配置文件中配置hibernateTemplate
<!-- 配置hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
6、在spring配置文件中配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
7、在spring配置文件中开启spring对注解事务的支持
<!-- 开启spring对注解事务的支持
(serviceimpl中)用@Transactional取代
-->
<tx:annotation-driven transaction-manager="transactionManager"/>
8、在客户的业务层实现类上使用@Transactional注解
@Service("customerService")
@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
public class ICustomerServiceImpl implements ICustomerService {
@Resource(name="customerDao")
private ICustomerDao customerDao;
//注入dao,被@Resource注解取代
/* public void setCustomerDao(ICustomerDao customerDao) {
this.customerDao = customerDao;
}*/
@Override
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public List<Customer> findAllCustomer() {
return customerDao.findAllCustomer();
}
@Override
public void saveCustomer(Customer customer) {
customerDao.saveCustomer(customer);
}
}
2、hibernate映射使用注解配置实现
1、实体类映射注解配置
@Entity
@Table(name="cst_customer")
public class Customer implements Serializable {
@Id
@Column(name="cust_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long custId;
@Column(name="cust_name")
private String custName;
2、spring中SessionFactory配置修改
<!-- 配置sessionFactory:让spring接管sessionFactory的创建
用spring提供的一个SessionFactory:LocalSessionFactoryBean
创建SessionFactory有三部分必不可少的信息。三部分信息在hibernate主配置文件中都有。
把hibernate主配置文件的位置注入进来
-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 第一部分:连接数据库的 用连接池-->
<property name="dataSource" ref="dataSource"></property>
<!-- 第二部分:hibernate的可选配置 -->
<property name="hibernateProperties">
<props>
<prop key=""></prop>
<!-- 数据库的方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 是否显示hibernate生成的SQL语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否使用格式化输出sql语句到控制台 -->
<prop key="hibernate.format_sql">false</prop>
<!-- 配置hibernate采用何种方式生成DDL语句 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 把session和线程绑定,从而实现一个线程只有一个Session -->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!-- 第三部分:映射文件的位置
mappingResources:它是一个注入string数组类型的数据。提供的是映射文件的位置。有几个映射文件,就需要写几个。
mappingDirectoryLocations:它是注入一个Resource类型的数组。提供的是映射文件所在的目录。此属性一般多用于一个项目有多个地方存放映射配置。
//服务端
server_domain
//移动端
mobile_domain
mappingLocations:它是注入一个Resource类型的数组。提供的映射文件的位置。它可以使用通配符。
-->
<!-- 指定实体类所在的包,当创建SessionFactory,会去该包中扫描实体类上的注解,从而生成映射配置 -->
<!—指定扫描映射注解的包-->
<property name="packagesToScan">
<array>
<value>com.fzy.entity</value>
</array>
</property>
</bean>
3、struts2配置使用注解实现
1、导入struts2注解的jar包
2、使用注解配置Action
两种方式:
@Controller("customerAction")
@Scope("prototype")
//-------以下都是struts2的注解-----------
@ParentPackage("struts-default")//指定当前包的父包
@Namespace("/customer")//指定名称空间,访问当前action的所有方法都需要有名称空间
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
private Customer customer = new Customer();
@Autowired
private ICustomerService customerService;
@Override
public Customer getModel() {
return customer;
}
private List<Customer> customers;
//用于配置动作名称
@Action(value="findAllCustomer",results={
@Result(name="findAllCustomer",
type="dispatcher",
location="/jsp/customer/list.jsp")
})
public String findAllCustomer(){
customers = customerService.findAllCustomer();
return "findAllCustomer";
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
@Controller("customerAction")
//取代struts.xml中的配置
@ParentPackage("struts-default")
@Namespace("/customer")
@Results({
@Result(name="addUICustomer",type="dispatcher",location="/jsp/customer/add.jsp"),
@Result(name="findAllCustomer",type="dispatcher",location="/jsp/customer/list.jsp"),
@Result(name="listCustomer",type="redirectAction",location="/findAllCustomer")
})
public class CustomerAction extends ActionSupport implements
ModelDriven<Customer> {
private Customer customer = new Customer();
private List<Customer> customers;
@Resource(name="customerService")
private ICustomerService customerService;
@Override
public Customer getModel() {
return customer;
}
//保存添加用户
@Action("addCustomer")
public String addCustomer(){
customerService.saveCustomer(customer);
return "listCustomer";
}
//查询所有客户
@Action("findAllCustomer")
public String findAllCustomer() {
customers = customerService.findAllCustomer();
return "findAllCustomer";
}
//获取添加客户页面
@Action("addUICustomer")
public String addUICustomer() {
return "addUICustomer";
}
//==========================================
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
精简:
ssh环境搭建
1、环境准备
1)、创建JavaWeb工程(2.5)导入所需jar包
2)、创建数据库和表结构(见readme/sql/customer-linkman.sql)
3)、创建工作包结构entity,dao,service,action
4)、编写实体类Customer.java,Linkman.java
5)、编写持久层接口CustomerDao.java(Interface)及其实现类CustomerDaoImpl.java
6)、编写业务层接口CustomerService.java(Interface)及其实现类CustomerServiceImpl.java
7)、编写Action,CustomerAction.java
一、基于xml的独立式整合
8)、编写Customer.hbm.xml映射文件(包扫描,实体类与数据表结构映射)
9)、编写web.xml(spring监听器,struts的核心控制器)
10)、编写hibernate核心配置文件hibernate.cfg.xml
(连接数据库的信息:driver_class,url,username,password,dialect
hibernate的可选配置:是否显示生成的sql语句
是否格式化输出sql语句到控制台
hibernate采用何种方式生成DDL语句
hibernate的连接池供应商
(session与线程的绑定,实现一个线程只有一个session)
与spring整合
映射文件的配置:映射配置文件的位置)
11)、编写struts.xml(开启开发者模式,配置动作)
12)、编写application.xml
(配置service,配置dao,配置hibernateTemplate,配置sessionFactory
配置事务管理器,配置事务的通知,配置aop(配置切入点表达式,建立切入点表达式和事务通知的关联))
13)、导入静态页面及布局
问题:导入伊始,会报JavaWeb:
报错信息The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
原来Javaweb工程类中没有添加Tomcat运行时相关类导致。
下面是具体的解决方法:
1、右击web工程-》属性或Build Path-》Java Build Path->Libraries-> Add Libray...->Server Runtime -》Tomcat Server
2、切换到Java Build Path界面中的Orader and Export,选择Tomcat。
注意:
按以上方法操作时,若打开Server Runtime后一片空白,需要设置Apache服务器。
设置方法为:window->Preferences->Server->Runtime Environment -> add --> 选择Apache的版本后点Next,再填入你apache服务器软件的安装(解压后)地址。
14)、出现问题,尚未完成,静待解决
二、基于XML的引入式整合
所谓:引入式整合就是把hibernate.cfg.xml中的配置都写在spring的配置文件中
<!-- 基于XML的独立式整合............................ -->
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
-->
<!-- .......................................... -->
<!-- 基于XML的引入式整合
所谓:引入式整合就是把hibernate.cfg.xml中的配置都写在spring的配置文件中
-->
<!-- start================================================ -->
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 第一部分:连接数据库的 用连接池-->
<property name="dataSource" ref="dataSource"></property>
<!-- 第二部分:hibernate的可选配置 -->
<property name="hibernateProperties">
<props>
<prop key=""></prop>
<!-- 数据库的方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 是否显示hibernate生成的SQL语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否使用格式化输出sql语句到控制台 -->
<prop key="hibernate.format_sql">false</prop>
<!-- 配置hibernate采用何种方式生成DDL语句 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 把session和线程绑定,从而实现一个线程只有一个Session -->
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
</props>
</property>
<!-- 第三部分:映射文件的位置
mappingResources:它是一个注入string数组类型的数据。提供的是映射文件的位置。有几个映射文件,就需要写几个。
mappingDirectoryLocations:它是注入一个Resource类型的数组。提供的是映射文件所在的目录。此属性一般多用于一个项目有多个地方存放映射配置。
//服务端
server_domain
//移动端
mobile_domain
mappingLocations:它是注入一个Resource类型的数组。提供的映射文件的位置。它可以使用通配符。
-->
<property name="mappingLocations">
<array>
<value>classpath:com/fzy/entity/*.hbm.xml</value>
</array>
</property>
</bean>
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- end===================================================== -->
三、基于注解的整合
所谓:注解整合使用上面的环境,把xml文件的配置全部换位注解方式
spring的注解整合分为两种方式:xml文件和纯注解
hibernate注解整合是把实体类映射改为JPA注解映射
1、整合步骤:spring使用xml文件
(spring配置使用注解实现)
1、导入必备jar包
2、在spring配置文件中导入context名称空间及约束
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
3、在spring配置文件中配置要扫描的包
<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="com.fzy"></context:component-scan>
4、注解配置action、service、dao
5、在spring配置文件中配置hibernateTemplate
<!-- 配置hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
6、在spring配置文件中配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
7、在spring配置文件中开启spring对注解事务的支持
<!-- 开启spring对注解事务的支持
(serviceimpl中)用@Transactional取代
-->
<tx:annotation-driven transaction-manager="transactionManager"/>
8、在客户的业务层实现类上使用@Transactional注解
2、hibernate映射使用注解配置实现
1、实体类映射注解配置
@Entity
@Table(name="cst_customer")
public class Customer implements Serializable {
@Id
@Column(name="cust_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long custId;
@Column(name="cust_name")
private String custName;
2、spring中SessionFactory配置修改
<!-- 指定实体类所在的包,当创建SessionFactory,会去该包中扫描实体类上的注解,从而生成映射配置 -->
<!—指定扫描映射注解的包-->
<property name="packagesToScan">
<array>
<value>com.fzy.entity</value>
</array>
</property>
</bean>
3、struts2配置使用注解实现
1、导入struts2注解的jar包
2、使用注解配置Action
两种方式:(在类的声明前面注解配置Action及跳转页面
在方法的前面注解配置Action及跳转页面)