加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

spring+springmvc+hibernate整合实例

发布时间:2020-12-15 07:10:54 所属栏目:Java 来源:网络整理
导读:最近要弄一个自动化生成表及其实体对应的增删改查的框架,于是我想到了hibernate,hibernate就有根据实体自动建表,而且增删改查,都不需要想mybatis那样在xml文件中配置。 不过怎样让该框架通过前端一个表单页面配置,从而让后台对应的生成,这个我还没想明

最近要弄一个自动化生成表及其实体对应的增删改查的框架,于是我想到了hibernate,hibernate就有根据实体自动建表,而且增删改查,都不需要想mybatis那样在xml文件中配置。

不过怎样让该框架通过前端一个表单页面配置,从而让后台对应的生成,这个我还没想明白,不过说到这,不得不提传统的ssh框架,传统的ssh框架,通常是指spring+struts2+hibernate或spring+struts+hibernate

不过想到struts2就有恐惧感,太多的action和xml配置,比较繁琐,不如springmvc来的痛快。所以我想这也许是struts2现在用的人数不如springmvc多的原因之一。当然,也不能说struts2就不好了,据说struts2(struts)+spring+hibernate称之为最经典的mvc框架。

说到MVC,M指的是模型,V指的是视图,C值的控制器,通俗的理解,可以这么说,视图通过控制器的到模型(数据),这让我想到了JSP+Servlet+JDBC。jsp负责展示数据,servet处理前端请求,与jdbc交互,将数据返回给jsp。

目前MVC在互联网用的比较广。

不多说了,来一波整合吧。好久没整这个都忘记了,写一个作纪念,同时万一以后业务需要,省的去找,同时也给大家学习借鉴使用

一、准备环境

JDK8 Maven tomcat7(tomcat8)都行 mysql5.5以上

二、pom文件

<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/xsd/maven-4.0.0.xsd">
    modelVersion>4.0.0</groupId>cn.pms.sshartifactId>ssh_pmsversion>0.0.1-SNAPSHOTpackaging>war>



    dependencies>
   dependency>
        >org.projectlombok>lombok>1.16.10scope>provided>
      <!-- hibernate配置 -->
        >
            >org.hibernate>hibernate-core>5.2.12.Final>

         hibernate 缓存,视情况添加 -->
         <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>4.3.5.Final</version>
        </dependency>  单元测试 >junit>3.8.1>test spring核心包 >org.springframework>spring-test>4.3.13.RELEASE>spring-webmvc>spring-core>
        
         https://mvnrepository.com/artifact/org.springframework/spring-orm >spring-orm>4.3.1.RELEASE>
        
        
        >spring-aop>aspectj>aspectjweaver>1.5.4>aspectjrt>org.codehaus.jackson>jackson-mapper-asl>1.9.11>mysql>mysql-connector-java>5.1.21>c3p0>0.9.1.2type>jar打印日志 >org.slf4j>slf4j-api>1.7.5>slf4j-log4j12>log4j>1.2.17>jstl>1.2>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.13.RELEASE</version>

        </dependency> -->
        
            >spring-context>


         https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api >javax.servlet.jsp>jsp-api>2.1 javax.servlet-api >javax.servlet>javax.servlet-api>3.1.0 spring-web >spring-web spring-webmvc  阿里巴巴fastjson >com.alibaba>fastjson>1.2.41dbcp >org.apache.commons>commons-dbcp2>2.1.1 辅助 >com.google.code.gson>gson>2.2.4>commons-lang3>3.3.2>




    >


    buildpluginsplugin>
                >org.apache.maven.plugins>maven-compiler-plugin>2.0.2configuration>
                    source>1.8target>



        finalName>${project.artifactId}>

project>

?

三、建立实体和DAO

package com.ssh.entity;

import lombok.Data;

import javax.persistence.*;

/**
 * Created by XRog
 * On 2/2/2017.2:03 PM
 */
@Data
@Entity
@Table(name = "Person")
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "created")
    private Long created = System.currentTimeMillis();

    @Column(name = "username" String username;

    @Column(name = "address" String address;

    @Column(name = "phone" String phone;

    @Column(name = "remark" String remark;

    public Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = Long getCreated() {
         created;
    }

     setCreated(Long created) {
        this.created = String getUsername() {
         username;
    }

     setUsername(String username) {
        this.username = String getAddress() {
         address;
    }

     setAddress(String address) {
        this.address = String getPhone() {
         phone;
    }

     setPhone(String phone) {
        this.phone = String getRemark() {
         remark;
    }

     setRemark(String remark) {
        this.remark = remark;
    }
    
    
}

?

 com.ssh.repository;

 java.io.Serializable;
 java.util.List;


 * Created by XRog
 * On 2/2/2017.2:28 PM
 */
interface DomainRepository<T,PK extends Serializable>{
    T load(PK id);

    T get(PK id);

    List<T> findAll();

     persist(T entity);

    PK save(T entity);

     saveOrUpdate(T entity);

     delete(PK id);

     flush();
}
 com.ssh.entity.Person;


 * Created by XRog
 * On 2/2/2017.2:25 PM
 interface PersonRepository extends DomainRepository<Person,Long> {
}

?

三、建立业务接口及其实现类

 com.ssh.service;


 * Created by XRog
 * On 2/2/2017.2:39 PM
 interface PersonService {
    Long savePerson();
    
    Person getId(Long id);
    
     delete(Long id);
}

?

 com.ssh.repository.impl;

 javax.persistence.Query;

 org.hibernate.Session;
 org.hibernate.SessionFactory;

 org.springframework.beans.factory.annotation.Autowired;
 org.springframework.stereotype.Repository;

 com.ssh.entity.Person;
 com.ssh.repository.PersonRepository;


 * Created by XRog
 * On 2/2/2017.2:30 PM
 
@Repository
class PersonRepositoryImpl implements PersonRepository {

    @Autowired
     SessionFactory sessionFactory;

     Session getCurrentSession() {
        return this.sessionFactory.openSession();
    }

     Person load(Long id) {
        return (Person)getCurrentSession().load(Person.,id);
    }

     Person get(Long id) {
        return (Person)getCurrentSession().get(Person.public List<Person> findAll() {
       Query query = getCurrentSession().createQuery("select * from user");
         query.getResultList();
    }

     persist(Person entity) {
        getCurrentSession().persist(entity);
    }

     Long save(Person entity) {
         (Long)getCurrentSession().save(entity);
    }

     saveOrUpdate(Person entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

     delete(Long id) {
        Person person = load(id);
        getCurrentSession().delete(person);
    }

     flush() {
        getCurrentSession().flush();
    }
}

?

四、ssh框架相关的xml和properties配置

applicationContext.xml配置如下:

beans ="http://www.springframework.org/schema/beans"
       xmlns:xsi
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    ********************************************配置Spring*************************************** 自动扫描 context:component-scan base-package="com.ssh" 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
            context:exclude-filter ="annotation" expression="org.springframework.stereotype.Controller"/>
        context:component-scan********************************************配置hibernate********************************************-->

    扫描配置文件(这里指向的是之前配置的那个config.properties)-->
    context:property-placeholder location="classpath:/config.properties" />

    配置数据源bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"property name="driverClass" value="${jdbc.driver}" />  数据库连接驱动="jdbcUrl"="${jdbc.url}" />     数据库地址="user"="${jdbc.username}" />   用户名="password"="${jdbc.password}" 密码="maxPoolSize"="40" />      最大连接数="minPoolSize"="1" />       最小连接数="initialPoolSize"="10" 初始化连接池内的数据库连接="maxIdleTime"="20" 最大空闲时间bean配置session工厂="sessionFactory"="org.springframework.orm.hibernate4.LocalSessionFactoryBean" ref="dataSource" ="packagesToScan"="com.ssh.entity" ="hibernateProperties"props>
                
                prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}prop> hibernate根据实体自动生成数据库表-->
                ="hibernate.dialect">${hibernate.dialect}>   指定数据库方言="hibernate.show_sql">${hibernate.show_sql}>     在控制台显示执行的数据库操作语句="hibernate.format_sql">${hibernate.format_sql}在控制台显示执行的数据哭操作语句(格式)-->
      
            property>
          
     事物管理器配置  ="transactionManager"="org.springframework.orm.hibernate4.HibernateTransactionManager"="sessionFactory" />
    beans>

?

config.properties文件如下:

#database connection config
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = 1234

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

?

spring-mvc.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>

    xmlns:xsi
    xmlns:context
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc
    xmlns:task="http://www.springframework.org/schema/task"  
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/task  
        http://www.springframework.org/schema/task/spring-task-3.1.xsd"  扫描Controller层 ="com.ssh.controller"/>
    
    mvc:default-servlet-handler 开启注解 mvc:annotation-driven />
    
    
     对模型视图名称的解析,即在模型视图名称添加前后缀 ="org.springframework.web.servlet.view.InternalResourceViewResolver"="prefix"="/WEB-INF/view/" ="suffix"=".jsp" />可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 >

     
>  

?

五、Controller

 com.ssh.controller;

 org.springframework.stereotype.Controller;
 org.springframework.web.bind.annotation.RequestMapping;
 org.springframework.web.bind.annotation.RequestMethod;
 org.springframework.web.bind.annotation.ResponseBody;

 com.ssh.entity.User;
 com.ssh.service.PersonService;
 com.ssh.service.UserService;



 * Created by XRog
 * On 2/1/2017.12:36 AM
 
@Controller
 MainController {

    @Autowired
     PersonService personService;

    @Autowired
     UserService userService;
    
    @RequestMapping(value = "savePerson",method = RequestMethod.GET)
    @ResponseBody
     String savePerson(){
       return "success";
    }
}

?

六、数据表

/*
SQLyog Ultimate v8.32 
MySQL - 5.7.20-log : Database - ssh
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS,UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE,SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES,SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssh` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `ssh`;

/*Table structure for table `person` */

DROP TABLE IF EXISTS `person`;

CREATE TABLE `person` (
  `id` bigint(20) NOT NULL,`address` varchar(255) DEFAULT NULL,`created` bigint(20) DEFAULT NULL,`phone` varchar(255) DEFAULT NULL,`remark` varchar(255) DEFAULT NULL,`username` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `person` */

insert  into `person`(`id`,`address`,`created`,`phone`,`remark`,`username`) values (1,'1',1,'1');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

?

七、配置web.xml文件

web-app xmlns:xsi
         xmlns="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"
         version="3.0" 地址为http://localhost:8080/  显示的默认网页welcome-file-list>
          welcome-file>/index.jsp加载Spring的配置文件到上下文中去context-paramparam-name>contextConfigLocationparam-value>
                classpath:applicationContext.xml
             spring MVC config startservletservlet-name>springservlet-class>org.springframework.web.servlet.DispatcherServletinit-param>
               此处指向的的是SpringMVC的配置文件 -->
              >classpath:spring-mvc.xml配置容器在启动的时候就加载这个servlet并实例化load-on-startup>1servlet-mappingurl-pattern>/ spring MVC config end-->


         Spring监听器 listenerlistener-class>org.springframework.web.context.ContextLoaderListener  字符集过滤  filterfilter-name>encodingFilterfilter-class>org.springframework.web.filter.CharacterEncodingFilter>encoding>UTF-8>forceEncoding>truefilter-mapping>/*web-app>

?

八、启动项目无报错,在浏览器输入对应的requestMapping名字,返回success内容表示成功

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读