整合Hibernate和spring需要的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Maven_SSH</groupId>
<artifactId>Maven_SSH</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Maven_SSH Maven Webapp</name>
<url>http://maven.apache.org</url>
<!-- 改版本用 properties里面的键可以随便写 -->
<properties>
<spring.version>4.3.10.RELEASE</spring.version>
<struts.version>2.3.33</struts.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 引入Servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0-b07</version>
<scope>provided</scope>
</dependency>
<!-- 加入hibernate核心库 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- 引入MySQL依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
<!-- 加入Spring核心库依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring整合Hibernate依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring 的AspectJ依赖,解析事务切点 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 加入c3p0数据库连接池依赖 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- 引入struts2依赖 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts.version}</version>
</dependency>
<!-- struts2整合Spring插件的整合包 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${struts.version}</version>
</dependency>
<!--json-lib依赖-->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies>
<build>
<finalName>Maven_SSH</finalName>
</build>
</project>
第一步:把Hibernate写好,先把Hibernate需要的依赖导进来,写一个entity的类
package com.zking.entity;
public class Person {
private int pid;
private String pname;
private String psex;
private int page;
public Person() {
}
public Person(int pid) {
this.pid = pid;
}
public Person(String pname, String psex, int page) {
this.pname = pname;
this.psex = psex;
this.page = page;
}
public Person(int pid, String pname, String psex, int page) {
super();
this.pid = pid;
this.pname = pname;
this.psex = psex;
this.page = page;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPsex() {
return psex;
}
public void setPsex(String psex) {
this.psex = psex;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
}
在写一个person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-8-29 21:34:37 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.zking.entity.Person" table="PERSON">
<id name="pid" type="int">
<column name="PID" />
<generator class="native" />
</id>
<property name="pname" type="java.lang.String">
<column name="PNAME" />
</property>
<property name="psex" type="java.lang.String">
<column name="PSEX" />
</property>
<property name="page" type="int">
<column name="PAGE" />
</property>
</class>
</hibernate-mapping>
在把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.password">root</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property> <property name="hibernate.connection.username">root</property> --> <property name="show_sql">true</property> <property name="format_sql">true</property>
<!-- <mapping resource="com/zking/entity/Person.hbm.xml"/> --> </session-factory></hibernate-configuration> 最后把Hibernate测试一下再把spring的依赖导进来<!-- 整合之后就不要了 -->
package com.zking.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.zking.entity.Person; public class TestHibernate { @Test public void test(){ Configuration configuration=new Configuration().configure(); SessionFactory sessionFactory=configuration.buildSessionFactory(); Session session=sessionFactory.openSession(); Transaction transaction=session.beginTransaction(); session.save(new Person("郁郁", "男", 41)); transaction.commit(); session.close(); sessionFactory.close(); } }
第二步:写一个db.properties,连接数据库用的,不过这一步还没有和数据库连接
所有我们要写一个applicationContext-public.xml,在这里面引入db.propertiesuname=root upass=root url=jdbc:mysql://localhost:3306/test driver_class=com.mysql.jdbc.Driver initPoolSize=3 maxPoolSize=20
spring的applicationContext不只可以写applicationContext-public.xml,还可以有dao、biz、action等名字可以随便写,但是要“applicationContext-”要一致,否则会报错。<?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-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 1.引入db.properties --> <context:property-placeholder location="classpath:db.properties"/> <!-- 2.配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${uname}"></property> <property name="password" value="${upass}"></property> <property name="jdbcUrl" value="${url}"></property> <property name="driverClass" value="${driver_class}"></property> <property name="initialPoolSize" value="${initPoolSize}"></property> <property name="maxPoolSize" value="${maxPoolSize}"></property> </bean> <!-- 3.配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 01.引入数据源 --> <property name="dataSource" ref="dataSource"></property> <!-- 02.加载Hibernate配置文件 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 03.加载Hibernate映射文件 --> <property name="mappingLocations" value="classpath:com/zking/entity/*.hbm.xml"></property> </bean> <!-- 4.配置事务 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 5.配置事务的属性 --> <!-- 事务的底层是advice通知 --> <tx:advice id="myAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- propagation="REQUIRED"需要有属性 --> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 6.配置事务的切点 --> <aop:config> <aop:pointcut expression="execution(* com.zking.dao.*.*(..))" id="myCut"/> <aop:advisor advice-ref="myAdvice" pointcut-ref="myCut"/> </aop:config> </beans>
applicationContext-dao.xml
applicationContext-biz.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 配置personDaoImp --> <bean id="personDaoImp" class="com.zking.dao.PersonDaoImp"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
applicationContext-action.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 配置personBizImp --> <bean id="personBizImp" class="com.zking.biz.PersonBizImp"> <property name="personDao" ref="personDaoImp"></property> </bean> </beans>
在这我就只写dao方法了,其他的和以前差不多,只是在里面我们不是用new了,用的是注入举个栗子:在biz里我们要调用dao里的方法:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 配置PersonAction --> <bean id="personAction" class="com.zking.action.PersonAction" scope="prototype"> <property name="personBiz" ref="personBizImp"></property> </bean> </beans>
public PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}//添加
public void addPerson(Person person) {
personDao.addPerson(person);
}
package com.zking.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.zking.entity.Person; public class PersonDaoImp implements PersonDao{ //注入一个sessionFactory private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession(){ return sessionFactory.getCurrentSession(); } //添加 public void addPerson(Person person) { Person users=new Person(person.getPname(), person.getPsex(), person.getPage()); Serializable Serializable = getSession().save(users); int a=(Integer) Serializable; System.out.println(a); } //修改 public void updatePerson(Person person) { Person persons=getSession().get(Person.class, person.getPid()); persons.setPname(person.getPname()); persons.setPsex(person.getPsex()); persons.setPage(person.getPage()); getSession().update(persons); } //删除 public void deletePerson(int pid) { Person person=new Person(); person.setPid(pid); getSession().delete(person); } //查询 public List<Person> getAll() { //查询所有 List<Person> list=getSession().createQuery("from Person").list(); return list; } //分页查询 public List<Person> getAll(int pageNo, int pageSize) { //分页 List<Person> list=getSession().createQuery("from Person").setFirstResult((pageNo-1)*pageSize).setMaxResults(pageSize).list(); return list; } public int IntCount() { int n=Integer.parseInt(getSession().createQuery("select count(*) from Person").uniqueResult().toString()); return n; } }
在写一个personAction.java
package com.zking.action; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.zking.biz.PersonBiz; import com.zking.entity.Person; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class PersonAction extends ActionSupport{ HttpServletResponse resp=ServletActionContext.getResponse(); HttpServletRequest req=ServletActionContext.getRequest(); private Person person; private PersonBiz personBiz; private int pid; private String pname; private String psex; private int page; //添加 public String add() throws Exception { System.out.println("进来了PersonAction。。。add"); resp.setContentType("text/html; charset=UTF-8"); req.setCharacterEncoding("UTF-8"); personBiz.addPerson(new Person(pname, psex, page)); return null; } //修改 public String update() throws Exception{ System.out.println("进来了PersonAction。。。update"); resp.setContentType("text/html; charset=UTF-8"); req.setCharacterEncoding("UTF-8"); personBiz.updatePerson(new Person(pname, psex, page)); return null; } //删除 public String delete() throws Exception{ System.out.println("进来了PersonAction。。。delete"); resp.setContentType("text/html; charset=UTF-8"); req.setCharacterEncoding("UTF-8"); System.out.println(pid); personBiz.deletePerson(pid); return null; } //分页查询 public String select() throws IOException{ resp.setContentType("text/html; charset=UTF-8"); //设置当前页 int intPage =new Integer(req.getParameter("page")); //设置每页显示的数量 int intPageSize =new Integer(req.getParameter("rows")); List<Person> list=personBiz.getAll(intPage, intPageSize); int n=personBiz.IntCount(); JSONArray jsonarray=JSONArray.fromObject(list); JSONObject js=new JSONObject(); js.put("total", ""+n); js.put("rows", jsonarray); PrintWriter pw=resp.getWriter(); pw.write(js.toString()); pw.close(); return null; } public PersonBiz getPersonBiz() { return personBiz; } public void setPersonBiz(PersonBiz personBiz) { this.personBiz = personBiz; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getPsex() { return psex; } public void setPsex(String psex) { this.psex = psex; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } }
写好了spring之后进行springHibernate的测试
第三步:与Struts2整合,写一个struts.xmlpackage com.zking.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zking.dao.PersonDao; import com.zking.entity.Person; public class TestSpringHibernate { @Test public void test1(){ ApplicationContext ac=new ClassPathXmlApplicationContext(new String[]{"applicationContext-public.xml","applicationContext-dao.xml"}); PersonDao personDao=(PersonDao) ac.getBean("personDaoImp"); personDao.addPerson(new Person("李里", "男", 30)); } }
我用easyui写了一个简单的增删改查的页面<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="mypackage" extends="struts-default"> <action name="personAtion*" class="personAction" method="{1}"></action> </package> </struts>
还要配置web.xml<%@ page language="java" contentType="text/html; charset=UTF-8" 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>Insert title here</title> <!-- 引入easyui库 --> <link rel="stylesheet" type="text/css" href="easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="easyui/themes/icon.css"> <script type="text/javascript" src="easyui/jquery.min.js"></script> <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript"> var DBindex; $(function(){ $('#dg').datagrid({ url:'personAtionselect.action', pagination: true, //显示分页 pageSize: 3, //页大小 pageList: [3, 6, 9, 11], //页大小下拉选项此项各value是pageSize的倍数 fitColumn: true, //列自适应宽度 striped: true, //行背景交换 nowap: true, //列内容多时自动折至第二行 nowrap : false, idField: 'pid', //主键 loadMsg:'正在拼命加载中...', columns:[[ {field:'pid',title:'编号',width:75,align:'center'}, {field:'pname',title:'姓名',width:75,align:'center',"editor":{type:'validatebox'}}, {field:'psex',title:'性别',width:75,align:'center',"editor":{type:'validatebox'}}, {field:'page',title:'年龄',width:75,align:'center',"editor":{type:'validatebox'}}, ]],onDblClickRow:function(index,row){ DBindex=index; $('#dg').datagrid('beginEdit',index); },onClickRow:function(index,row){ DBindex=index; },toolbar: [{ iconCls: 'icon-add', text:"添加", handler: function(){ DBindex=0; $('#dg').datagrid('insertRow',{ index:0, // 索引从0开始 row: {} }); $('#dg').datagrid('beginEdit',0); } },'-',{ iconCls: 'icon-remove', text:"删除", handler: function(){ var row=$('#dg').datagrid("getRows")[DBindex]; if(row!=null){ var pid=row["pid"]; $.post("personAtiondelete.action", {"pid":pid}, function(data){ $('#dg').datagrid('reload'); }); } } },'-',{ iconCls: 'icon-save', text:"保存", handler: function(){ $('#dg').datagrid('endEdit',DBindex); var row=$('#dg').datagrid("getRows")[DBindex]; if(row!=null){ var pname=row["pname"]; var psex=row["psex"]; var page=row["page"]; $.post("personAtionadd.action", {"pname":pname,"psex":psex,"page":page}, function(data){ $('#dg').datagrid('reload'); }); } } },'-',{ iconCls: 'icon-edit', text:"修改", handler: function(){ $('#dg').datagrid('endEdit',DBindex); var row=$('#dg').datagrid("getRows")[DBindex]; if(row!=null){ var pid=row["pid"]; var pname=row["pname"]; var psex=row["psex"]; var page=row["page"]; $.post("personAtionupdate.action", {"pid":pid,"pname":pname,"psex":psex,"page":page}, function(data){ $('#dg').datagrid('reload'); }); } } }] }); }); </script> </head> <body> <div align="center"> <table id="dg" style="width:301px;height:500px"></table> </div> </body> </html>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!-- 加载spring alt+\ 必须按照context-param->filter->listener的顺序来--> <!-- needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-*.xml</param-value> </context-param> <!-- 加载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>*.action</url-pattern> </filter-mapping> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>