今天小编很开心,因为学习springMVC基础的路终于走到了尽头,也成功搭建了一个SSH框架,暗自在心里默默地开心了1秒钟。

  好了,回归正题:整合Hibernate.上一节,我为大家分享我整合spring的学习笔记,今天我讲的是接着上一节继续进行学习的,所以不熟悉上一节内容的读者,可以先看一下上一节的内容(http://www.cnblogs.com/juin1058/p/6490267.html),再过来围观。

1.整合Hibernate

1.1 事先准备,导入Hibernate的相关jar包:

  antlr-2.7.7.jar,

  aopalliance.jar,

  dom4j-1.6.1.jar,

  hibernate-commons-annotations-4.0.1.Final.jar,

  hibernate-core-4.1.6.Final.jar,

  hibernate-jpa-2.0-api-1.0.1.Final.jar,

  javassist-3.15.0-GA,

  jboss-logging.jar,

  jboss-transaction-api_1.1_spec-1.0.0.Final.jar.

这些jar包网上搜索一下就可以找到下载。

1.2 新建实体类User

 package com.juin.entity;

 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.Id;
 import javax.persistence.Table;

 import org.hibernate.annotations.GenericGenerator;

 @Entity
 @Table(name="user")
 public class User {

     @Id
     @GeneratedValue(generator = "system-uuid")
     @GenericGenerator(name = "system-uuid", strategy = "uuid")
     @Column(length=32)
     private String id;

     @Column(length=32)
     private String username;

     @Column(length=32)
     private String psw;

     public String getId() {
         return id;
     }

     public void setId(String id) {
         this.id = id;
     }

     public String getUsername() {
         return username;
     }

     public void setUsername(String username) {
         this.username = username;
     }

     public String getPsw() {
         return psw;
     }

     public void setPsw(String psw) {
         this.psw = psw;
     }

 }

com.juin.entity:User.java

1.3 新建hibernate映射文件

 <!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>
         <mapping class="com.juin.entity.User"/>
     </session-factory>
 </hibernate-configuration>

hibernate.cfg.test.xml

1.4 新建hibernate配置文件,数据库用的是mysql

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
 <!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
 ]>

 <beans>
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
         <property name="url" value="jdbc:mysql://localhost:3306/test"/>
         <property name="username" value="juin"/>
         <property name="password" value="123654"/>
     </bean>

     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
         <property name="dataSource" ref="dataSource"/>
         <property name="hibernateProperties">
             <props>
                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                 <prop key="hibernate.hbm2ddl.auto">update</prop>
                 <prop key="hibernate.show_sql">true</prop>
                 <prop key="hiberante.format_sql">true</prop>
             </props>
         </property>
         <property name="configLocations">
             <list>
                 <value>
                     classpath*:hibernate/hibernate.cfg.test.xml
                 </value>
             </list>
         </property>
     </bean>

     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name="sessionFactory" ref="sessionFactory"></property>
     </bean>

     <bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
         <property name="transactionManager" ref="transactionManager"></property>
         <property name="transactionAttributes">
             <props>
                 <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
                 <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
                 <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
                 <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
                 <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
                 <prop key="get*">PROPAGATION_NEVER</prop>
             </props>
         </property>
     </bean>

 </beans>

springAnnotation-hibernate.xml

到这里,hibernate算是整合完毕了,下面自然是进行一些简单的数据操作啦!!!

2 .简单的数据库操作

  调整一下整体结构,如下图:

  

小编比较懒,就直接贴代码了,想要源码的评论区留联系方式。

1.springAnnotion-import.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
 <!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
 ]>

 <beans>
     <bean id="userDao" class="com.juin.dao.UserDAO">
         <property name="sessionFactory" ref="sessionFactory"></property>
     </bean>

     <bean id="userManagerBase" class="com.juin.service.UserManager">
         <property name="userDao" ref="userDao"></property>
     </bean>

     <bean id="userManager" parent="transactionBase">
         <property name="target" ref="userManagerBase"></property>
     </bean>

 </beans>

springAnnotion-import.xml

2.springAnnotion-core.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
 <!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
 ]>

 <beans>
     <import resource="classpath*:spring/springAnnotation-import.xml"/>
 </beans>

springAnnotion-core.xml

3.springAnnotion-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  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.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

     <!-- 扫描指定包下的所有类 -->
     <context:component-scan base-package="com.juin.controller"/>
     <!-- 启用注解的两个bean -->
     <mvc:annotation-driven/>
     <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
     <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->
     <!-- 静态文件访问 -->
     <mvc:resources location="/img/" mapping="/img/**"/>
     <mvc:resources location="/js/" mapping="/js/**"/>
     <mvc:resources location="/css/" mapping="/css/**"/>

     <!-- 文件上传 -->
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
           <property name="defaultEncoding" value="utf-8" />
           <property name="maxUploadSize" value="10485760000" />
           <property name="maxInMemorySize" value="40960" />
     </bean>

     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix" value="/"></property>
         <property name="suffix" value=".jsp"></property>
     </bean>
  </beans>  

springAnnotion-servler.xml

4.IUserDAO

 package com.juin.dao;

 import java.util.List;

 import com.juin.entity.User;

 public interface IUserDAO {
     public void addUser(User user);
     public boolean delUser(String id);
     public List<User> getAllUser();
 }

IUser接口

5.UserDAO实现IUserDAO接口

 package com.juin.dao;

 import java.util.List;

 import org.hibernate.Query;
 import org.hibernate.SessionFactory;

 import com.juin.entity.User;

 public class UserDAO implements IUserDAO {

     private SessionFactory sessionFactory;

     public SessionFactory getSessionFactory() {
         return sessionFactory;
     }

     public void setSessionFactory(SessionFactory sessionFactory) {
         this.sessionFactory = sessionFactory;
     }

     @Override
     public void addUser(User user) {
         sessionFactory.getCurrentSession().save(user);
     }

     @Override
     public List<User> getAllUser() {

         String hql="from User";
         Query query = sessionFactory.getCurrentSession().createQuery(hql);
         return query.list();
     }

     @Override
     public boolean delUser(String id) {
         String hql = "delete  User u where u.id=?";
         Query query = sessionFactory.getCurrentSession().createQuery(hql);
         query.setString(0, id);
         return query.executeUpdate()>0;
     }

 }

UserDAO

6.IUserManager

 package com.juin.service;

 import java.util.List;

 import com.juin.entity.User;

 public interface IUserManager {
     public void addUser(User user);
     public boolean deleteUser(String id);
     public List<User> getAllUser();
 }

IUserManager接口

7.UserManager实现IUserManager接口

 package com.juin.service;

 import java.util.List;

 import com.juin.dao.IUserDAO;
 import com.juin.entity.User;

 public class UserManager implements IUserManager {

     private IUserDAO userDao;

     public void setUserDao(IUserDAO userDao) {
         this.userDao = userDao;
     }

     @Override
     public void addUser(User user) {
         userDao.addUser(user);
     }

     @Override
     public List<User> getAllUser() {
         // TODO Auto-generated method stub
         return userDao.getAllUser();
     }

     @Override
     public boolean deleteUser(String id) {
         return userDao.delUser(id);
     }

 }

UserManager

8.定义UserController

 package com.juin.controller;

 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.List;

 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;

 import com.juin.entity.User;
 import com.juin.service.IUserManager;

 @Controller
 @RequestMapping("/user")
 public class UserController {
     @Resource(name = "userManager")
     private IUserManager userManager;

     @RequestMapping("/addUser")
     public String addUser(User user) {
         userManager.addUser(user);
         return "/success";
     }

     @RequestMapping("/getAllUser")
     public String getAllUser(HttpServletRequest request) {
         List<User> user = userManager.getAllUser();
         request.setAttribute("user", user);
         return "/userManager";
     }

     @RequestMapping("/delUser")
     public void delUser(String id, HttpServletResponse response) {
         String result = "{\"result\":\"error\"}";
         if (userManager.deleteUser(id)) {
             result = "{\"result\":\"success\"}";
         }
         PrintWriter out = null;
         response.setContentType("application/json");

         try {
             out = response.getWriter();
             out.write(result);
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

     @RequestMapping("/toUser")
     public String toUser() {
         return "/addUser";
     }
 }

UserController

最后是对应的jsp页面,如下图

1.addUser.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Insert title here</title>
 <script type="text/javascript">
     function addUser(){
         var form = document.forms[0];
         form.action="/SpringMVC8/user/addUser";
         form.method="post";
         form.submit();
     }
 </script>
 </head>
 <body>
     <h>添加用户</h>
     <form name="userForm" action="">
         姓名:<input type="text" name="username">
         密码:<input type="text" name="psw">
         <input type="button" value="添加" onclick="addUser()">
     </form>
 </body>
 </html>

addUser

2.userManager.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Insert title here</title>
 <script type="text/javascript">
     function del(id) {
         $.get("/SpringMVC8/user/delUser?id=" + id, function(data) {
             alert(data.result);
             if ("success" == data.result) {
                 alert("删除成功!");
                 window.location.reload();
             } else {
                 alert("删除失败!")
             }
         });
     }
 </script>
 </head>
 <body>
     <table border="1">
         <tbody>
             <tr>
                 <th>姓名</th>
                 <th>密码</th>
                 <th>编辑</th>
             </tr>
             <c:if test="${!empty user }">
                 <c:forEach items="${user }" var="u">
                     <tr>
                         <td>${u.username }</td>
                         <td>${u.psw }</td>
                         <td><a href="javascript:void(0)">编辑</a> <a
                             href="javascript:del('${u.id }')">删除</a></td>
                     </tr>
                 </c:forEach>
             </c:if>
         </tbody>

     </table>
 </body>
 </html>

userManager.jsp

3.success.jsp

 你开心就好

success.jsp

最新文章

  1. 将.war文件解压到指定目录
  2. UIPopoverController使用
  3. JAVA求解线性方程组-列主元高斯消去法
  4. WPF,Silverlight与XAML读书笔记第四十五 - 外观效果之模板
  5. 本地MVC项目发布到IIS服务器
  6. hadoop: hive 1.2.0 在mac机上的安装与配置
  7. Linux下编译安装Apache Http Server
  8. Android JNI开发生成.h头文件问题(转)
  9. Mac下使用Automator实现隐藏和显示
  10. 第九篇 ERP实施项目中需求分析及方案设计的通用思路
  11. RTSP协议学习笔记
  12. 【原】Oracle拼接字段
  13. Spring笔记之(一)初探
  14. Servlet和JSP读书笔记(二)
  15. Erlang常用代码段
  16. 【Revit API】梁构件支座检查算法
  17. oracle导入TYPE对象报错ORA-02304
  18. 解决ajaxfileupload上传文件在IE浏览器返回data为空问题
  19. 【Beta Scrum】冲刺!5/5
  20. twitter ads_campaign management

热门文章

  1. MySQL的SQL预处理(Prepared)
  2. CentOS 7下安装samba
  3. 在IE中启动火狐——自定义浏览器链接协议
  4. ECharts(中国地图篇)的使用
  5. 深入理解Java虚拟机(笔记)
  6. PHP(数据类型、水仙花数(重点)运算符)
  7. java中基本类型double和对象类型Double
  8. centOs6.5配置启动ssh
  9. [No000017F]如何监控注册表的修改
  10. Compile caffe on unbutu 16.0.4