工程目录:
/SSH1/src/cn/itcast/domain/Book.java
package cn.itcast.domain; /** * 图书 */ public class Book { private Integer id; // 图书编号 private String name; // 图书名称 private Double price; // 图书价格 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
/SSH1/src/cn/itcast/domain/Book.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="cn.itcast.domain.Book" table="book"> <id name="id"> <generator class="identity"></generator> </id> <property name="name"></property> <property name="price"></property> </class> </hibernate-mapping>
/SSH1/src/cn/itcast/dao/BookDAO.java
package cn.itcast.dao; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import cn.itcast.domain.Book; /** * 数据层代码 */ public class BookDAO extends HibernateDaoSupport { public void save(Book book) { System.out.println("添加图书 dao 执行..."); this.getHibernateTemplate().save(book); } }
/SSH1/src/cn/itcast/service/BookService.java
package cn.itcast.service; import org.springframework.transaction.annotation.Transactional; import cn.itcast.dao.BookDAO; import cn.itcast.domain.Book; /** * 图书管理 业务层 */ @Transactional public class BookService { private BookDAO bookDAO; public void addBook(Book book) { System.out.println("添加图书 service执行 ..."); bookDAO.save(book); } public void setBookDAO(BookDAO bookDAO) { this.bookDAO = bookDAO; } }
/SSH1/src/cn/itcast/web/action/BookAction.java
package cn.itcast.web.action; import cn.itcast.domain.Book; import cn.itcast.service.BookService; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * 添加图书 */ public class BookAction extends ActionSupport implements ModelDriven<Book> { private static final long serialVersionUID = 1L; private Book book = new Book(); public Book getModel() { return book; } @Override public String execute() throws Exception { System.out.println("添加图书 action 执行... "); bookService.addBook(book); return NONE; } private BookService bookService; public void setBookService(BookService bookService) { this.bookService = bookService; } }
/SSH1/src/applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 配置Action --> <bean id="bookAction" class="cn.itcast.web.action.BookAction" scope="prototype"> <property name="bookService" ref="bookService"/> </bean> <!-- 配置Service --> <bean id="bookService" class="cn.itcast.service.BookService"> <property name="bookDAO" ref="bookDAO"/> </bean> <!-- 配置DAO --> <bean id="bookDAO" class="cn.itcast.dao.BookDAO"> <!-- 注入sessionFactory, 构造hibernateTemplate --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 整合hibernate 方式一 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean> <!-- 事务管理 --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans>
/SSH1/src/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> <!-- JDBC基本连接参数 --> <session-factory> <!-- 理解为连接池 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 配置方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 常见其它配置 --> <property name="hibernate.show_sql">true</property> <!-- 控制台上打印SQL --> <property name="hibernate.format_sql">true</property> <!-- 控制台输出时,对SQL语句格式化 --> <!-- 测试环境 create/ create-drop 正式环境 update validate --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 自动建表 --> <property name="hibernate.connection.autocommit">true</property> <!-- 在核心配置文件中 引用 mapping 映射文件 --> <mapping resource="cn/itcast/domain/Book.hbm.xml"/> </session-factory> </hibernate-configuration>
/SSH1/src/log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
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' ###
log4j.rootLogger=info, stdout
/SSH1/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> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!-- 方式一,自动向Action 装配 Service --> <!-- <action name="addbook" class="cn.itcast.web.action.BookAction"></action> --> <!-- 方式二,将Action 交给Spring 管理 , class属性 编写伪类名 --> <action name="addbook" class="bookAction"></action> </package> </struts>
/SSH1/WebRoot/WEB-INF/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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name></display-name> <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>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> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.do,*.action</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>welcome.jsp</welcome-file> </welcome-file-list> </web-app>
/SSH1/WebRoot/book.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>addBook</title> </head> <body> <h1>添加图书</h1> <s:form action="addbook" namespace="/" method="post" theme="simple"> 图书名称 <s:textfield name="name"></s:textfield> <br /> 图书价格 <s:textfield name="price"></s:textfield> <br /> <s:submit type="submit" value="提交"></s:submit> </s:form> </body> </html>
/SSH1/WebRoot/success.jsp
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>success</title> </head> <body> <h1>ADDBOOK SUCCESS!</h1> </body> </html>
/SSH1/WebRoot/welcome.jsp
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加图书</title> </head> <body> <a href="/SSH1/addbook">显示</a> <a href="book.jsp">book.jsp</a> </body> </html>
下载:http://download.csdn.net/detail/chenwei1510347223/7383157
HibernateTemplate使用
Hibernate Session API 被 Spring 提供 HibernateTemplate 简化
以后的开发中 将直接使用 HibernateTemplate 的API
最常用 API
Serializable save(Object entity) : 保存
void update(Object entity) : 修改
void delete(Object entity) : 删除
<T> T get(Class<T> entityClass, Serializable id) : 根据id 查询 (立即查询)
<T> T load(Class<T> entityClass, Serializable id) : 根据id查询 (默认延迟查询)
List find(String queryString, Object... values) : 根据hql查询
List findByCriteria(DetachedCriteria criteria) : 使用离线条件查询 ----------- 重点
List findByNamedQuery(String queryName, Object... values) : 使用命名查询语句 ------------ 重点
***** 6、 OpenSessionInViewFilter使用
OpenSessionInView 为了解决 延迟加载问题
BookDAO
// 返回延迟加载对象
public Book findByIdLazy(Integer id) {
return this.getHibernateTemplate().load(Book.class, id);
}
如果业务层管理事务,Action查询对象属于脱管态对象,如果延迟加载,抛出no Session 异常
解决 :
<!-- OpenSessionInView -->
<filter>
<filter-name>OpenSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
BookDAO.java
package cn.itcast.dao; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import cn.itcast.domain.Book; /** * 数据层代码 */ public class BookDAO extends HibernateDaoSupport { // save public void save(Book book) { System.out.println("添加图书 dao 执行..."); this.getHibernateTemplate().save(book); } // update public void update(Book book) { this.getHibernateTemplate().update(book); } // delete public void delete(Book book) { this.getHibernateTemplate().delete(book); } // getload public Book findById(Integer id) { return this.getHibernateTemplate().get(Book.class, id); } public List<Book> findAll() { // 简化session.createQuery return this.getHibernateTemplate().find("from Book"); } // 离线条件查询 public List<Book> findDetachedCriteria(DetachedCriteria detachedCriteria) { // 简化session.createQuery return this.getHibernateTemplate().findByCriteria(detachedCriteria); } // findByNameQuery public List<Book> findByName(String name) { // findByName配置查询语句名称 // name是参数 return this.getHibernateTemplate().findByNamedQuery("findByName", name); } // 返回延迟加载对象 public Book findByIdLazy(Integer id) { return this.getHibernateTemplate().load(Book.class, id); } }
Book.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="cn.itcast.domain.Book" table="book"> <id name="id"> <generator class="identity"></generator> </id> <property name="name"></property> <property name="price"></property> </class> <!-- 名称查询 --> <query name="findByName"> <![CDATA[from Book where name = ?]]> </query> </hibernate-mapping>
BookDAOTest.java
package test; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.itcast.dao.BookDAO; import cn.itcast.domain.Book; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext.xml") public class BookDAOTest { @Autowired @Qualifier("bookDAO") private BookDAO bookDAO; @Test public void textUpdate(){ Book book=new Book(); book.setId(1); book.setName("精通ssh"); book.setPrice(80d); bookDAO.update(book); } @Test public void textDelete(){ Book book=new Book(); book.setId(1); book.setName("精通ssh"); book.setPrice(80d); bookDAO.delete(book); } @Test public void textFindById(){ Book book= bookDAO.findById(2); System.out.println(book); } @Test public void textFindDetachedCriteria(){ DetachedCriteria detachedCriteria=DetachedCriteria.forClass(Book.class); detachedCriteria.add(Restrictions.like("name", "%s%")); List<Book> books= bookDAO.findDetachedCriteria(detachedCriteria); for(Book book:books) System.out.println(book); } @Test public void testNamedQuery(){ List<Book> books= bookDAO.findByName("Chen"); for(Book book:books) System.out.println(book); } }