首页 > 其他分享 >Spring4 MVC Hibernate4集成

Spring4 MVC Hibernate4集成

时间:2023-03-28 15:02:58浏览次数:44  
标签:Hibernate4 hibernate name lei MVC user import public Spring4


一、    本文所用环境

Spring4.0.3.RELEASE

Hibernate4.3.5.Final

Mysql

二、    工程目录

 

Spring4 MVC Hibernate4集成_hibernate

三、    Maven添加依赖

用Maven创建项目,pom.xml如下:

View Code

四、    新建数据库表

数据库采用Mysql,新建users表,我们演示操作此表


CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) DEFAULT NULL,
  `nice_name` varchar(32) DEFAULT NULL,
  `user_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


创建Entity类Users.java见下


package com.lei.demo.entity;

import javax.persistence.*;

@Entity(name="users")
public class Users {
    
    public Users(){
        super();
    }
    
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private Integer id;
    
    @Column(name="user_name",length=32)
    private String user_name;
    
    @Column(name="age")
    private Integer age;
    
    @Column(name="nice_name",length=32)
    private String nice_name;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUser_name() {
        return user_name;
    }
    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getNice_name() {
        return nice_name;
    }
    public void setNice_name(String nice_name) {
        this.nice_name = nice_name;
    }
}


 

五、    配置文件

1.        首先看一下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" 
    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>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 定义DispatcherServlet -->
  <servlet>
    <servlet-name>lei-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!-- 默认/WEB-INF/[servlet名字]-servlet.xml加载上下文, 
          如果配置了contextConfigLocation参数,
          将使用classpath:/lei-dispatcher-servlet.xml加载上下文
      -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:/lei-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 拦截匹配的请求,这里所有请求采用名字为lei-dispatcher的DispatcherServlet处理 -->
  <servlet-mapping>
    <servlet-name>lei-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


 

2.        lei-dispatcher-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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        ">
        
    <!-- 启动自动扫描该包下所有的Bean(例如@Controller) -->
    <context:component-scan base-package="com.lei.demo" />
    
    <!-- 定义视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/user/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
</beans>


 

3.        Spring-hibernate的整合

spring-hibernate.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        ">

    <!-- Hibernate4 -->
    <!-- 加载资源文件  其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->
    <context:property-placeholder location="classpath:persistence-mysql.properties" />
    
    <bean id="sessionFactory" 
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <!-- 可以加多个包 -->
                <value>com.lei.demo.entity</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <!--  <prop key="hibernate.current_session_context_class">thread</prop> --> 
            </props>
        </property>
    </bean>
    
    <!-- 数据库映射 -->
    <!--  class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" -->
    <!--  class="org.springframework.jdbc.datasource.DriverManagerDataSource" -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="${jdbc.driverClassName}" />
      <property name="url" value="${jdbc.url}" />
      <property name="username" value="${jdbc.user}" />
      <property name="password" value="${jdbc.pass}" />
   </bean>
   
    <!-- 配置Hibernate事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="sessionFactory" />
   </bean>
   
   <!-- 配置事务异常封装 -->
   <bean id="persistenceExceptionTranslationPostProcessor" 
       class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
   
   <!--  声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="get*" propagation="REQUIRED" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    
    <aop:config expose-proxy="true">
        <!-- 只对业务逻辑层实施事务 -->
        <aop:pointcut id="txPointcut" expression="execution(* com.lei.demo.service..*.*(..))" />
        <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->
        <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
    </aop:config>
    
</beans>


事务采用tx:advice和aop:config的xml配置方式实现。事务的其他实现方式见Spring MVC事务配置》

 

资源文件persistence-mysql.properties如下:


# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://yourServerIP:3306/yourDatabase?createDatabaseIfNotExist=true
jdbc.user=user
jdbc.pass=password

# hibernate.X
hibernate.connection.driverClass=org.gjt.mm.mysql.Driver
hibernate.connection.url=jdbc:mysql:// yourServerIP:3306/yourDatabase
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.connection.username=user
hibernate.connection.password=password
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop


 

六、    DAO、Service

UsersDAO.java如下:


package com.lei.demo.dao;

import java.util.List;

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

import com.lei.demo.entity.Users;

public class UsersDAO {
    private SessionFactory sessionFactory;

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

    public List<Users> getAllUser(){
        String hsql="from users";
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery(hsql);
        
        return query.list();
    }
}


 

UserService.java如下:


package com.lei.demo.service;

import com.lei.demo.dao.*;

public class UserService {
    private UsersDAO userDao;
    
    public int userCount(){
        return userDao.getAllUser().size();
    }

    public UsersDAO getUserDao() {
        return userDao;
    }

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

}


Spring4 MVC Hibernate4集成_Java_02


 

七、    加载Bean配置文件

这里主要是加载上边的dao、service


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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.2.xsd
        http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.2.xsd">
      
    <bean id="usersDAO" class="com.lei.demo.dao.UsersDAO">
          <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="userService" class="com.lei.demo.service.UserService">
        <property name="userDao" ref="usersDAO"></property>
    </bean>
</beans>

 

当然你也可以不采用xml配置bean,采用注释加载bean,见Spring3系列7- 自动扫描组件或BeanSpring 开启Annotation <context:annotation-config>  <context:component-scan>诠释及区别》

 

八、    JSP页面和Controller

WEB-INF/user/users.jsp如下:


<%@ 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>
</head>
<body>
    <h1>Message : ${message}</h1>
</body>
</html>

 

写Controller访问上边的jsp


package com.lei.demo.controller;

import javax.annotation.Resource;

import com.lei.demo.service.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
public class UserController {
    
    @Resource(name="userService")
    private UserService service;
    
    @RequestMapping(value="/manager",method=RequestMethod.GET)
    public ModelAndView hello2(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", "HelloMVC");
        mv.setViewName("users");
        return mv;
    }
    
    @RequestMapping(value="/count",method=RequestMethod.GET)
    public ModelAndView count(){
        
        int c = service.userCount();
        
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", c);
        mv.setViewName("users");
        return mv;
    }
}



上边的controller定义了两个路径

http://localhost:8080/spring4-mvc-hibernate4/user/manager

http://localhost:8080/spring4-mvc-hibernate4/user/count

以上两个路径都调用WEB-INF/user/users.jsp

参考资料《Spring3系列13-Controller和@RequestMapping》

 

九、    运行结果

 

Spring4 MVC Hibernate4集成_spring_03

Spring4 MVC Hibernate4集成_Java_04

 



 

标签:Hibernate4,hibernate,name,lei,MVC,user,import,public,Spring4
From: https://blog.51cto.com/u_2650279/6154909

相关文章

  • SpringMVC 大文件上传解决方案(500M以上)
    javaweb上传文件上传文件的jsp中的部分上传文件同样可以使用form表单向后端发请求,也可以使用ajax向后端发请求    1.通过form表单向后端发送请求        ......
  • MVCC机制
    事务的四个特征(ACID)事务具有四个特征:原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)和持续性(Durability)。这四个特性简称为ACID特性。原子性。事务是......
  • 【Spring MVC】请求处理过程
    1 前言前面分析了SpringMVC的创建过程,本章分析SpringMVC是怎么处理请求的。我们这里分两步:首先分析HtpServletBean、FrameworkServlet和DispatcherServlet这......
  • SpringMVC快速入门与详解
    一、SpringMVC简介1.概念 SpringMVC是一种基于Java的实现MVC设计模式的Web框架,该框架通过将Web应用程序划分为模型、视图和控制器来简化Web应用程序的开发......
  • MySQL MVCC
    目录前言共享锁和排它锁什么是当前读和快照读?当前读快照读MVCCReadView流程RR、RC生成ReadView的时机总结前言MVCC,全称Multi-VersionConcurrencyControl,即多版本并......
  • 【SpringMVC】RESTFurl风格交互方式+Ajax交互
    第一章RESTFurl风格交互方式(重要)第一节RESTFurl概述1.REST的概念REST:RepresentationalStateTransfer,表现层资源状态转移。定位:互联网软件架构风格倡导者:RoyThomasFi......
  • SpringMVC-lesson08-json-3-2023-03-24
    阿里巴巴开发的JSON<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.60</version></dependency>@Request......
  • SpringMVC-lesson08-json-2-2023-03-24
    公共类packagecom.feijian.utils;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.f......
  • SpringMVC-lesson08-json-2023-03-24
    1\JSON复习<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><scripttype="text/javascript">varuser={......
  • SpringMVC-lesson07-乱码问题-2023-03-24
    一、TOMCATCONFIG文件配置:<Connectorport="8080"protocol="HTTP/1.1"connectionTimeout="20000"redirectPort="8443"URIEncoding="UTF-8"/>二、springmvc自带过滤配......