hibernate持久化框架(Spring+springMVC+hibernate)

来源:互联网 发布:淘宝限购一件怎么设置 编辑:程序博客网 时间:2024/06/05 11:33

一、什么是hibernate

hibernate是一个持久化框架,ORM框架,JDBC框架,处于我们MVC架构下的dao层,是对我们jdbc的一个封装,hibernate将数据库的表与java的实体通过关系映射进行管理和维护,帮我们简化了我们数据库的CRUD操作,但是任何东西都是相对的,我们的 操作被简化了。那我们的程序的效率就降低了。同时在hibernate里面我们需要自己手动控制事务,
由于我们实际开发都是BS(浏览器/服务器),我们一般都是SSH联合开发,struts2(表现层)+spring3.0-(容器框架) + hiberante(持久层),当然伴随着我们springMVC的出现,struts2的使用频率已经比较低了。所以我们以
springMVC+Spring+Hibernate 来进行入门:

二、hibernate入门案例

1、软件下载:spring3.2 + hibernate4.2,自行到github下载
这里写图片描述

2、新建一个web项目,目录如下:
这里写图片描述

3、导入spring下的所有jar包,由于spring3.2集成了我们的springMVC,所以相当于我们spring的jar包和springMVC的jar包是已经全部完成。
这里写图片描述

同时导入所有hiberante的lib下面的required下面的所有jar包

这里写图片描述
required:表示必须的包,其他的都是一些辅助包,暂时用不到
4、配置spring和springmvc,首先配置web.xml,主要我们spring的监听器和springmvc的总控制器

<?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" id="WebApp_ID" version="3.0">  <display-name>TestHibernate1.0.0</display-name>  <!-- Spring和mybatis的配置文件 -->      <context-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:config/spring*.xml</param-value>      </context-param>  <!-- spring监听器 -->   <listener>         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>     </listener>   <!-- springMVC的总控制器 -->  <servlet>        <servlet-name>controller</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:config/spring*.xml</param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>controller</servlet-name>        <url-pattern>*.do</url-pattern>    </servlet-mapping>  <welcome-file-list>    <welcome-file>index.html</welcome-file>  </welcome-file-list></web-app>

配置我们的spring.xml ,此处我们最好讲spring的xml分成各个模块来进行配置,
a、在src的config下新建一个spring-mvc.xml配置如下

<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"  xmlns:mvc="http://www.springframework.org/schema/mvc"  xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd    http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  ">    <!-- 启用mvc注解 -->    <mvc:annotation-driven></mvc:annotation-driven>    <!-- Bean在那个包下面 -->    <context:component-scan base-package="com.xingxue.*"/>    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/pages/"/><!-- 前缀 -->        <property name="suffix" value=".jsp"/><!-- 后缀 -->    </bean></beans>

b、在我们config下新建一个spring-hibenrate.xml,配置如下:

<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"  xmlns:mvc="http://www.springframework.org/schema/mvc"  xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd    http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  ">  <!-- 整合hiberante -->  <!-- 接管我们hibernate的sessionFactory -->  <bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">    <!-- spring管理的数据源 -->    <property name="dataSource" ref="c3p0dateSource"></property>    <!-- hibernate的配置文件 -->    <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>  </bean>  <!-- c3p0数据源配置 -->  <bean name="c3p0dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>    <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8"></property>    <property name="user" value="root"></property>    <property name="password" value="root"></property>  </bean>  <!-- 事务管理 -->    <!-- spring事务配置 -->  <!-- 配置事务管理器 -->  <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" >    <property name="sessionFactory" ref="sessionFactory"></property>  </bean>  <!-- 配置事务处理策略 -->  <tx:advice id="tx" transaction-manager="transactionManager">    <tx:attributes>        <tx:method name="update*"  rollback-for="Throwable"/>        <tx:method name="insert*"  rollback-for="Throwable"/>        <tx:method name="delete*"  rollback-for="Throwable"/>    </tx:attributes>  </tx:advice>  <!-- 配置我们的事务通知机制 -->  <aop:config>    <aop:pointcut expression="execution(* com.xingxue.service.*.*(..))" id="txpoint"/>    <aop:advisor advice-ref="tx" pointcut-ref="txpoint"/>  </aop:config></beans>

到此我们spring整合hiberante的配置就已经完成,

同时我们需要去对hibernate本身进行一些配置,在config下新建hiberante.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>        <!-- SQL方言        hiberante自己提供的数据库CRUD操作,是不需要我们编写sql代码的,        只需要调用对应的方法即可,hibernate就会根据对应的方法去自己生成        对应的SQL代码,所以我们需要指定方言,根据方言确定SQL语法生成SQL         -->        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>        <!--         当我们执行CRUD的时候是否把SQL代码在控制台打印         -->        <property name="show_sql">true</property>        <!--         我们hibernate未来会管理我们的表和实体类的关系,我们有可能表结构需要发生变化,    hiberante认为表应该以实体为准。    update:实体类发生变化就重新新建表    create:每次重启都先删除原来的表,然后在新建一张空表    hiberante是先有实体类,然后在根据实体类生成表。        这是hibernate的特色之一             -->        <property name="hbm2ddl.auto">update</property>    </session-factory></hibernate-configuration>

发布启动后发现我们的spring-hibernate.xml无法解析,原因是差了springAOP的依赖包,需要下载导入,jar仓库或者直接百度下载
这里写图片描述

再次启动就已经没有错误了。说明整合成功

测试一个查询功能:
新建一个login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'login.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    login Page<br>    <form action="<%=path %>/admin/login.do" method="post">        账号<input type="text" name="userName"> <br>        密码<input type="text" name="pwd"> <br>        <input type="submit" value="login"> <br>    </form>  </body></html>

新建一个AdminController

package com.xingxue.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controller@RequestMapping("/admin")public class AdminController {    @RequestMapping("login.do")    public ModelAndView login(String userName, String pwd) {        System.out.println(userName);        System.out.println(pwd);        ModelAndView mv = new ModelAndView();        mv.setViewName("ok");        mv.addObject("msg", "login Success");        return mv;    }}

新建一个ok.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'login.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>============    ${msg }  </body></html>

测试结果如下:

这里写图片描述
这里写图片描述
这里写图片描述

由此看出SpringMVC是通的。。。。。。。
下面利用hibernate实现登陆:
新建实体类Admin

package com.xingxue.entity;public class Admin {    private int id;    private String userName;    private String pwd;}

hibernate是把实体类和数据库的表关联起来的,目前为止提供了两种方式,
一种是通过xml来实现,
一种是通过注解来实现,
先说xml,我们hibernate一个实体类对应一个xml文件,所以新建一个Admin.hbm.xml

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping>    <!--     name:指代我们实体类的类路径    table:对应的数据库的表明     -->    <class name="com.xingxue.entity.Admin" table="xx_plat_admin">        <!-- 主键配置用id -->        <id column="admin_id" name="id">            <generator class="identity"></generator>        </id>        <!-- 普通属性用property -->        <property column="admin_usename" name="userName"></property>        <property column="admin_pwd" name="pwd"></property>    </class></hibernate-mapping>

这个xml的作用就是把数据库的xx_plat_admin表和我们com.xingxue.entity.Admin实体类的属性和字段给关联起来,

在hibernate.cfg.xml的配置文件中加入如下配置:

<mapping resource="com/xingxue/entity/Admin.hmb.xml"/>

编写dao代码来进行操作

package com.xingxue.dao.impl;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.xingxue.dao.AdminDao;import com.xingxue.entity.Admin;@Repository("adminDao")public class AdminDaoImpl implements AdminDao{    //拿到hibernate的工厂    @Autowired    private SessionFactory sessionFactory;    @Override    public Admin login(int adminId, String userName, String pwd) {        Session session = this.sessionFactory.openSession();        Admin admin = (Admin) session.get(Admin.class, adminId);        session.close();        return admin;    }}

同时修改controller,调用到dao,采用spring注解的方式实现

package com.xingxue.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.xingxue.dao.AdminDao;import com.xingxue.entity.Admin;@Controller@RequestMapping("/admin")public class AdminController {    @Autowired    private AdminDao adminDao;    @RequestMapping("login.do")    public ModelAndView login(String userName, String pwd) {        //调用dao完成登陆操作        Admin admin = this.adminDao.login(1,userName, pwd);        ModelAndView mv = new ModelAndView();        mv.setViewName("ok");        mv.addObject("msg", "login Success");        return mv;    }}

项目的目录结果如下:
这里写图片描述

然后测试,表被成功创建,
然后手动录入一条数据,
在次启动并测试,debug跟一下admin的结果,发现有数据,
整合完成,
hibernate配置成功

阅读全文
0 0
原创粉丝点击