本博客为这篇博客的辅助博客,主要是其中自己写的一些Demo.java代码
目录
整合Hibernate方法1,带有hibernate.cfg.xml的配置文件
整合Hibernate方法2.不带有hibernate.cfg.xml的配置文件.推荐使用
Hibernate的模板的常用的方法(基本和session一样查询的API)
SSH3大框架整合(保存客户为例)
整合Hibernate方法1,带有hibernate.cfg.xml的配置文件
Customer.java
package com.itheima.domain;
import java.util.ArrayList;
import java.util.List;
import com.sun.xml.internal.bind.util.Which;
public class Customer {
private Long cust_id;
private String cust_name;
private Long cust_user_id;
private Long cust_create_id;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_linkman;
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 Long getCust_user_id() {
return cust_user_id;
}
public void setCust_user_id(Long cust_user_id) {
this.cust_user_id = cust_user_id;
}
public Long getCust_create_id() {
return cust_create_id;
}
public void setCust_create_id(Long cust_create_id) {
this.cust_create_id = cust_create_id;
}
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_linkman() {
return cust_linkman;
}
public void setCust_linkman(String cust_linkman) {
this.cust_linkman = cust_linkman;
}
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;
}
@Override
public String toString() {
return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_user_id=" + cust_user_id
+ ", cust_create_id=" + cust_create_id + ", cust_source=" + cust_source + ", cust_industry="
+ cust_industry + ", cust_level=" + cust_level + ", cust_linkman=" + cust_linkman + ", cust_phone="
+ cust_phone + ", cust_mobile=" + cust_mobile + "]";
}
}
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.itheima.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_user_id" column="cust_user_id"/>
<property name="cust_create_id" column="cust_create_id"/>
<property name="cust_source" column="cust_source"/>
<property name="cust_industry" column="cust_industry"/>
<property name="cust_level" column="cust_level"/>
<property name="cust_linkman" column="cust_linkman"/>
<property name="cust_phone" column="cust_phone"/>
<property name="cust_mobile" column="cust_mobile"/>
</class>
</hibernate-mapping>
CustomerDao.java
package com.itheima.dao;
import com.itheima.domain.Customer;
public interface CustomerDao {
public void save(Customer customer);
}
CustomerDaoImpl.java
package com.itheima.dao;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.itheima.domain.Customer;
/**
* 客户的持久层
* @author 寒面银枪
* 2019年7月2日-下午8:22:52
*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
/*private HibernateTemplate hibernateTemplate;
public void setTemplate(HibernateTemplate hibernateTemplate) {
this.template = template;
}*/ //同样的道理 每写一个dao都写一个属性来注入 麻烦 提供一个父类 里面帮你写好了 直接继承即可
/**
* 保存客户
*/
public void save(Customer customer) {
System.out.println("持久层:保存客户...");
//把数据保存到数据库
/*HibernateTemplate template =new HibernateTemplate();
template.save(entity);//提示方法和session一模一样 说明底层就是封装了Hibernate的session
很明显不能自己new 赶紧去注入吧*/
getHibernateTemplate().save(customer);
}
}
CustomerService.java
package com.itheima.service;
import com.itheima.domain.Customer;
public interface CustomerService {
public void save(Customer customer);
}
CustomerServiceImpl.java
package com.itheima.service;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.dao.CustomerDao;
import com.itheima.domain.Customer;
/**
* 客户的业务层
* @author 寒面银枪
* 2019年7月2日-下午7:06:18
*/
@Transactional //下面的方法就都有了事务
public class CustomerServiceImpl implements CustomerService {
private CustomerDao customerDao;
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
/**
* 保存客户
*/
public void save(Customer customer) {
System.out.println("业务层:保存客户...");
customerDao.save(customer);
}
}
CustomerAction.java
package com.itheima.web.action;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.itheima.domain.Customer;
import com.itheima.service.CustomerService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
* 客户的控制层(web层)
* @author Administrator
*/
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
private static final long serialVersionUID = 1L;
/**
* 以后除非接收的单个参数使用属性驱动 否则都使用模型驱动封装数据 实现ModelDriven接口
* 多简单:实现接口 写一个javaBean属性 接口必须实现的方法内返回对象 即可
*/
private Customer customer=new Customer();//必须手动实例化
public Customer getModel() {
return customer;
}
//注入service 提供service成员属性
private CustomerService customerService;
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}//一旦Action给spring管理 Struts的自动注入就失效了 必须手动注入 既然Action在spring的xml中了 那么多配置一个属性就是了
/**
* 保存客户的方法
* @return
*/
public String add() {
System.out.println("web层保存客户...");
// WEB工厂 :将spring的在web.xml中配置监听器 然后服务器启动时创建一个单例(new完所有对象以及完成所有注入) 并且放到了ServletContext中 此时可以通过工具类直接获得这个唯一的工厂了
/*WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
CustomerService cs = (CustomerService) context.getBean("customerService");
cs.save(customer);*/
//第一天整合时就说过不是最终方案 因为依然很麻烦 开发时肯定不会用
//开发中肯定用注入的方式 直接在Action中注入service 然后直接拿来用 (struts注入和spring注入 建议使用后者)
//方法1:竟然直接提供一个属性+一个构造器就行了 这是struts2做到的 (struts-spring.jar包起的作用)
//其实就是按名称注入 因为applicationContext.xml里面的对象内存里都有了,struts可以根据名称将xml里的对象注入进来,只要和action里提供了set方法的属性名一致
customerService.save(customer);
//然而推荐使用的还是方法2,将action类也交给spring来管理 (最终达到3层的所有类都由spring管理)
return NONE;
}
}
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">
<!-- 编写一个名称固定的bean(spring提供的) 帮我们加载hibernate.cfg.xml的配置文件
这一个类一加载完,配置文件就加载完了 sessionFactory也创建好了
sessionFactory是重量级的,不能轻易销毁和创建,正好springIOC默认就是单例的
-->
<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">
<!--昨天传入连接池 今天就传入sessionFactory session能管理事务 -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置客户模块 -->
<!-- 配资客户的Action
特别强调:以后spring中配置Action,必须是多例的(值栈不能共享,一次请求一个) scope="prototype"
其他都是单例的,就action是多例的
-->
<bean id="customerAction" class="com.itheima.web.action.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"/>
</bean>
<!-- 配置客户的service -->
<bean id="customerService" class="com.itheima.service.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"/>
</bean>
<!-- 配置dao -->
<bean id="customerDao" class="com.itheima.dao.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 一番推导 发现继承HibernateDaoSupport 然后配置一个sessionFactory就行了
★ 以后ssh开发 dao都要继承HibernateDaoSupport 然后注入sessionFactory
-->
<!-- 模板也是一个类 需要先注入 -->
<!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
很明显 Hibernate的sessionFactory要给模板类 然后它才能封装啊
<property name="sessionFactory"></property>
</bean>
同理注入一个sessionFactory 就像连接池(数据库连接信息的那个)一样 建立时若父类发现hibernateTemplate为null,会帮我们创建一个
那么此处就可以省略模板的配置了 父类代码里会创建一个此对象
-->
</beans>
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>
<session-factory>
<!-- 必须配置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///day38_ssh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1111</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 可选配置 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置C3P0的连接池 -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 映射配置文件 -->
<mapping resource="com/itheima/domain/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
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">
<!-- 配置Action -->
<struts>
<!-- 先配置包结构 -->
<package name="crm" namespace="/" extends="struts-default">
<!-- Action由struts2来管理 -->
<!-- <action name="customer_*" class="com.itheima.web.action.CustomerAction" method="{1}"/> -->
<!-- Action由spring来管理,那么此处的class属性只写spring中的id值即可-->
<action name="customer_*" class="customerAction" method="{1}">
</action>
</package>
</struts>
整合Hibernate方法2.不带有hibernate.cfg.xml的配置文件.推荐使用
删除hibernate.cfg.xml,将相应的配置写入applicationContext.xml即可,所以代码仅配置最前面一部分不同
applicationContext.xml2
<?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">
<!-- 整合Hibernate方式2:将hibernate.cfg.xml的配置完全转移到这里来 -->
<!-- 先配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///day38_ssh"/>
<property name="user" value="root"/>
<property name="password" value="1111"/>
</bean>
<!-- 编写一个名称固定的bean(spring提供的) 帮我们加载hibernate.cfg.xml的配置文件
这一个类一加载完,配置文件就加载完了 sessionFactory也创建好了
sessionFactory是重量级的,不能轻易销毁和创建,正好springIOC默认就是单例的
-->
<!-- 使用LocalSessionFactoryBean加载配置 可以将一些hibernate.cfg.xml的配置移到此处的属性里 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 先加载连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载方言 加载可选项 -->
<property name="hibernateProperties"><!-- 里面配属性文件 写法有点不一样 -->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 最后引入映射的配置文件 -->
<property name="mappingResources">
<list>
<value>com/itheima/domain/Customer.hbm.xml</value>
<!-- <value>com/itheima/domain/Customer.hbm.xml</value> 数组就这么写多个 -->
</list>
</property>
</bean>
<!-- 事务模块 -->
<!-- 先配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<!--昨天传入连接池 今天就传入sessionFactory session能管理事务 -->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置客户模块 -->
<!-- 配资客户的Action
特别强调:以后spring中配置Action,必须是多例的(值栈不能共享,一次请求一个) scope="prototype"
其他都是单例的,就action是多例的
-->
<bean id="customerAction" class="com.itheima.web.action.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"/>
</bean>
<!-- 配置客户的service -->
<bean id="customerService" class="com.itheima.service.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"/>
</bean>
<!-- 配置dao -->
<bean id="customerDao" class="com.itheima.dao.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 一番推导 发现继承HibernateDaoSupport 然后配置一个sessionFactory就行了
★ 以后ssh开发 dao都要继承HibernateDaoSupport 然后注入sessionFactory
-->
<!-- 模板也是一个类 需要先注入 -->
<!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
很明显 Hibernate的sessionFactory要给模板类 然后它才能封装啊
<property name="sessionFactory"></property>
</bean>
同理注入一个sessionFactory 就像连接池(数据库连接信息的那个)一样 建立时若父类发现hibernateTemplate为null,会帮我们创建一个
那么此处就可以省略模板的配置了 父类代码里会创建一个此对象
-->
</beans>
Hibernate的模板的常用的方法(基本和session一样查询的API)
CustomerDaoImpl.java2
package com.itheima.dao;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.format.datetime.standard.DateTimeContextHolder;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.itheima.domain.Customer;
/**
* 客户的持久层
* @author 寒面银枪
* 2019年7月2日-下午8:22:52
*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
/*private HibernateTemplate hibernateTemplate;
public void setTemplate(HibernateTemplate hibernateTemplate) {
this.template = template;
}*/ //同样的道理 每写一个dao都写一个属性来注入 麻烦 提供一个父类 里面帮你写好了 直接继承即可
/**
* 保存客户
*/
public void save(Customer customer) {
System.out.println("持久层:保存客户...");
//把数据保存到数据库
/*HibernateTemplate template =new HibernateTemplate();
template.save(entity);//提示方法和session一模一样 说明底层就是封装了Hibernate的session
很明显不能自己new 赶紧去注入吧*/
getHibernateTemplate().save(customer);
}
/**
* 修改客户
*/
public void update(Customer customer) {
this.getHibernateTemplate().update(customer);
}
/**
* 通过主键查询客户 和session一模一样
*/
public Customer findById(Long id) {
return this.getHibernateTemplate().get(Customer.class, id);
}
/**
* 查询所有
*/
public List<Customer> finAll() {
List<Customer> list=(List<Customer>) this.getHibernateTemplate().find("from Customer");//写HQL语句
return list;
}
/**
* 查询所有 QBC方式 条件查询 Hibernate推荐的两种查询方式HQL和QBC
*/
@Override
public List<Customer> finAllByQBC() {
DetachedCriteria criteria=DetachedCriteria.forClass(Customer.class);
//criteria.add(Restrictions.eq("customer", name)); 不封装任何条件 就是查询所有
//需要参数:离线条件(脱离session就可以封装的条件 不是由session创建)
List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria);
return list;
}
}
Demo1.java
package com.itheima.test;
import java.util.List;
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.itheima.domain.Customer;
import com.itheima.service.CustomerService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {
@Resource(name="customerService")
private CustomerService cutomerService;
/**
* 演示修改
*/
@Test
public void run1() {
Customer customer=new Customer();
customer.setCust_id(1L);
customer.setCust_name("天青");
cutomerService.update(customer);
}
/**
* 演示查询
*/
@Test
public void run2() {
Customer customer = cutomerService.getById(2L);//ctrl+1->enter《=》ctrl+2->L
System.out.println(customer);
}
/**
* 查询所有客户
*/
@Test
public void run3() {
List<Customer> list = cutomerService.findAll();
for (Customer customer : list) {
System.out.println(customer);
}
}
/**
* 查询所有客户 QBC方式
*/
@Test
public void run4() {
List<Customer> list = cutomerService.findAllByQBC();
for (Customer customer : list) {
System.out.println(customer);
}
}
}
延时加载问题:
CustomerDaoImpl.java3
/**
* 演示延迟加载 使用load方法(想演示就不能使用get方法了)
*/
@Override
public Customer loadById(long id) {
/*Customer customer = this.getHibernateTemplate().load(Customer.class, id);
Hibernate.initialize(customer);//初始化 也即获得所有属性即 也即立即提交发送sql语句 不延迟加载了
return customer;*/
return this.getHibernateTemplate().load(Customer.class, id);
}
CustomerAction.java3
/**
* 演示延迟加载的问题
*/
public String loadById() {
Customer c=customerService.loadById(2L);
//打印客户名称
System.out.println(c.getCust_name());
/**
* 把包删除后又报no session异常 因为load方法延迟加载是你取它的属性时才发送sql语句,
* 但是service方法一调用完,事务就自动提交,session就关了,此时发sql语句,当然no session了
*
* 解决方法1:关闭延迟加载 <class name="com.itheima.domain.Customer" table="cst_customer" lazy="false">
* 解决方法2:Hibernate.initialize(customer);//把customer对象初始化 立即提交 不延迟了
* 前两种方法都不好,因为都强制取消了延迟加载,延迟加载提高效率的好处就没有了
*/
return NONE;
}
总结ssh的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>day38_ssh1</display-name>
<!-- 配置Spring框架整合web的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 此过滤器能解决延迟加载的问题 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置Struts2的核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</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-list>
</web-app>