<?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <!-- 配置EntityManagerFactor、并注入JPA持久化单元 --> <bean id="emf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" p:persistenceUnitName="books_pu"/> <!-- 该Bean后处理器会告诉Spring处理DAO组件中 @PersistenceContext注解, --> <bean class= "org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> <!-- 定义Service组件,并将DAO组件注入Service组件 --> <bean id="bookService" class="org.crazyit.booksys.service.impl.BookServiceImpl" p:bookDao-ref="bookDao"/> <!-- 定义DAO组件,并将SessionFactory注入DAO组件 --> <bean id="bookDao" class="org.crazyit.booksys.dao.impl.BookDaoJpa"/> <!-- 配置针对JPA的局部事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="emf"/> <!-- 根据事务注解来生成事务代理 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
<?xml version="1.0" encoding="GBK"?> <project name="spring" basedir="." default=""> <property name="src" value="src"/> <property name="dest" value="classes"/> <path id="classpath"> <fileset dir="lib"> <include name="**/*.jar"/> </fileset> <pathelement path="${dest}"/> </path> <target name="compile" description="Compile all source code"> <delete dir="${dest}"/> <mkdir dir="${dest}"/> <copy todir="${dest}"> <fileset dir="${src}"> <exclude name="**/*.java"/> </fileset> </copy> <javac destdir="${dest}" debug="true" includeantruntime="yes" deprecation="false" optimize="false" failonerror="true"> <src path="${src}"/> <classpath refid="classpath"/> <compilerarg value="-Xlint:deprecation"/> </javac> </target> </project>
<?xml version="1.0" encoding="GBK"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <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> </web-app>
<?xml version="1.0" encoding="GBK"?> <!-- 指定Struts 2配置文件的DTD信息 --> <!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.i18n.encoding" value="GBK"/> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true"/> <package name="lee" extends="struts-default"> <action name="addBook" class="org.crazyit.booksys.action.BookAction" method="add"> <!-- 添加图书成功,列出所有图书 --> <result type="chain">listBooks</result> <!-- 添加图书失败,跳转到添加图书的表单页 --> <result name="error">/WEB-INF/content/bookForm.jsp</result> </action> <action name="listBooks" class="org.crazyit.booksys.action.BookAction" method="list"> <result>/WEB-INF/content/listBooks.jsp</result> </action> <action name="deleteBook" class="org.crazyit.booksys.action.BookAction" method="delete"> <result type="chain">listBooks</result> </action> <!-- 让用户直接访问该应用时列出所有视图页面 --> <action name="*"> <result>/WEB-INF/content/{1}.jsp</result> </action> </package> </struts>
package org.crazyit.booksys.action; import java.util.List; import org.crazyit.booksys.domain.Book; import org.crazyit.booksys.service.BookService; import com.opensymphony.xwork2.ActionSupport; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class BookAction extends ActionSupport { private BookService bookService; // 依赖注入BookService组件必须的setter方法。 // 该方法的方法名要与BookService的配置id对应 public void setBookService(BookService bookService) { this.bookService = bookService; } private Book book; private List<Book> books; private int id; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } public int getId() { return id; } public void setId(int id) { this.id = id; } // 处理添加图书的add()方法 public String add() { System.out.println(bookService.getClass()); // 调用业务逻辑组件的addBook()方法来处理用户请求 bookService.addBook(book); int result = book.getId(); if(result > 0) { addActionMessage("恭喜您,图书添加成功!"); return SUCCESS; } addActionError("图书添加失败,请重新输入!"); return ERROR; } public String list() { setBooks(bookService.getAllBooks()); return SUCCESS; } public String delete() { System.out.println(bookService.getClass()); bookService.deleteBook(id); return SUCCESS; } }
package org.crazyit.booksys.dao; import java.util.List; import org.crazyit.booksys.domain.Book; import org.crazyit.common.dao.BaseDao; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public interface BookDao extends BaseDao<Book> { }
package org.crazyit.booksys.dao.impl; import java.util.List; import org.crazyit.booksys.dao.BookDao; import org.crazyit.booksys.domain.Book; import org.crazyit.common.dao.impl.BaseDaoJpa; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class BookDaoJpa extends BaseDaoJpa<Book> implements BookDao { }
package org.crazyit.booksys.domain; import javax.persistence.*; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ @Entity @Table(name="book_inf") public class Book { @Id @Column(name="book_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; @Column(name="book_name") private String name; private double price; private String author; 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; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
package org.crazyit.booksys.service; import java.util.List; import org.crazyit.booksys.domain.Book; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public interface BookService { // 添加图书 void addBook(Book book); List<Book> getAllBooks(); void deleteBook(int id); }
package org.crazyit.booksys.service.impl; import java.util.List; import javax.transaction.Transactional; import org.crazyit.booksys.dao.BookDao; import org.crazyit.booksys.domain.Book; import org.crazyit.booksys.service.BookService; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ @Transactional public class BookServiceImpl implements BookService { private BookDao bookDao; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } @Override public void addBook(Book book) { bookDao.save(book); } @Override public List<Book> getAllBooks() { return bookDao.findAll(Book.class); } @Override public void deleteBook(int id) { bookDao.delete(Book.class, id); } }
package org.crazyit.common.dao; import java.util.List; import java.io.Serializable; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public interface BaseDao<T> { // 根据ID加载实体 T get(Class<T> entityClazz , Serializable id); // 保存实体 Serializable save(T entity); // 更新实体 void update(T entity); // 删除实体 void delete(T entity); // 根据ID删除实体 void delete(Class<T> entityClazz , Serializable id); // 获取所有实体 List<T> findAll(Class<T> entityClazz); // 获取实体总数 long findCount(Class<T> entityClazz); }
package org.crazyit.common.dao.impl; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.crazyit.common.dao.BaseDao; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class BaseDaoJpa<T> implements BaseDao<T> { @PersistenceContext protected EntityManager entityManager; // 根据ID加载实体 public T get(Class<T> entityClazz , Serializable id) { return (T)entityManager.find(entityClazz , id); } // 保存实体 public Serializable save(T entity) { entityManager.persist(entity); try { return (Serializable) entity.getClass() .getMethod("getId").invoke(entity); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(entity + "必须提供getId()方法!"); } } // 更新实体 public void update(T entity) { entityManager.merge(entity); } // 删除实体 public void delete(T entity) { entityManager.remove(entity); } // 根据ID删除实体 public void delete(Class<T> entityClazz , Serializable id) { entityManager.createQuery("delete " + entityClazz.getSimpleName() + " en where en.id = ?0") .setParameter(0 , id) .executeUpdate(); } // 获取所有实体 public List<T> findAll(Class<T> entityClazz) { return find("select en from " + entityClazz.getSimpleName() + " en"); } // 获取实体总数 public long findCount(Class<T> entityClazz) { List<?> l = find("select count(*) from " + entityClazz.getSimpleName()); // 返回查询得到的实体总数 if (l != null && l.size() == 1 ) { return (Long)l.get(0); } return 0; } // 根据JPQL语句查询实体 @SuppressWarnings("unchecked") protected List<T> find(String jpql) { return (List<T>)entityManager.createQuery(jpql) .getResultList(); } // 根据带占位符参数JPQL语句查询实体 @SuppressWarnings("unchecked") protected List<T> find(String jpql , Object... params) { // 创建查询 Query query = entityManager.createQuery(jpql); // 为包含占位符的JPQL语句设置参数 for(int i = 0 , len = params.length ; i < len ; i++) { query.setParameter(i , params[i]); } return (List<T>)query.getResultList(); } /** * 使用JPQL语句进行分页查询操作 * @param jpql 需要查询的JPQL语句 * @param pageNo 查询第pageNo页的记录 * @param pageSize 每页需要显示的记录数 * @return 当前页的所有记录 */ @SuppressWarnings("unchecked") protected List<T> findByPage(String jpql, int pageNo, int pageSize) { // 创建查询 return entityManager.createQuery(jpql) // 执行分页 .setFirstResult((pageNo - 1) * pageSize) .setMaxResults(pageSize) .getResultList(); } /** * 使用JPQL语句进行分页查询操作 * @param jpql 需要查询的JPQL语句 * @param params 如果jpql带占位符参数,params用于传入占位符参数 * @param pageNo 查询第pageNo页的记录 * @param pageSize 每页需要显示的记录数 * @return 当前页的所有记录 */ @SuppressWarnings("unchecked") protected List<T> findByPage(String jpql , int pageNo, int pageSize , Object... params) { // 创建查询 Query query = entityManager.createQuery(jpql); // 为包含占位符的JPQL语句设置参数 for(int i = 0 , len = params.length ; i < len ; i++) { query.setParameter(i , params[i]); } // 执行分页,并返回查询结果 return query.setFirstResult((pageNo - 1) * pageSize) .setMaxResults(pageSize) .getResultList(); } }
<?xml version="1.0" encoding="GBK"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <!-- 为持久化单元指定名称,并通过transaction-type指定事务类型 transaction-type属性合法的属性值有JTA、RESOURCE_LOCAL两个--> <persistence-unit name="books_pu" transaction-type="RESOURCE_LOCAL"> <!-- 指定javax.persistence.spi.PersistenceProvider实现类 --> <provider>org.hibernate.ejb.HibernatePersistence</provider> <!-- 列出该应用需要访问的所有的Entity类, 也可以用<mapping-file>或<jar-file>元素来定义 --> <class>org.crazyit.booksys.domain.Book</class> <!-- properties元素用于为特定JPA实现包配置属性 --> <!-- 下面列举的是Hibernate JPA实现中可以配置的部分属性 --> <properties> <!-- 指定连接数据库的驱动名 --> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <!-- 指定连接数据库的URL --> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring"/> <!-- 指定连接数据库的用户名 --> <property name="hibernate.connection.username" value="root"/> <!-- 指定连接数据库的密码 --> <property name="hibernate.connection.password" value="32147"/> <!-- 指定连接数据库的方言 --> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/> <property name="hibernate.show_sql" value="true"/> <!-- 设置是否格式化SQL语句 --> <property name="hibernate.format_sql" value="true"/> <!-- 设置是否根据要求自动建表 --> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
<%-- 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> author yeeku.H.lee kongyeeku@163.com version 1.0 Copyright (C), 2001-2016, yeeku.H.Lee This program is protected by copyright laws. Program Name: Date: --%> <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>全部图书</title> </head> <body> <h3>全部图书</h3> <table width="640" border="1"> <s:iterator value="books" var="b"> <tr> <td><s:property value="name"/></td> <td><s:property value="price"/></td> <td><s:property value="author"/></td> <td><a href="${pageContext.request.contextPath}/deleteBook?id=${b.id}">删除</a></td> </tr> </s:iterator> </table> </body> </html>
<%-- 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> author yeeku.H.lee kongyeeku@163.com version 1.0 Copyright (C), 2001-2016, yeeku.H.Lee This program is protected by copyright laws. Program Name: Date: --%> <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>添加图书</title> </head> <body> <h3>添加图书</h3> <s:form action="addBook"> <s:textfield name="book.name" label="书名"/> <s:textfield name="book.price" label="价格"/> <s:textfield name="book.author" label="作者"/> <tr align="center"> <td colspan="2"> <s:submit value="添加" theme="simple"/> <s:reset value="重设" theme="simple"/> </td> </tr> </s:form> </body> </html>
来源:https://www.cnblogs.com/tszr/p/12373029.html