spring+springmvc+hibernate整合实例
最近要弄一个自动化生成表及其实体对应的增删改查的框架,于是我想到了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</modelVersion>
<groupId>cn.pms.ssh</groupId>
<artifactId>ssh_pms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<!-- hibernate配置 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency> <!-- hibernate 缓存, 视情况添加 -->
<!-- <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.5.Final</version>
</dependency> -->
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.13.RELEASE</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.1.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
</dependency>
<!--打印日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.13.RELEASE</version> </dependency> --> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency> <!-- javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency> <!-- spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.13.RELEASE</version>
</dependency> <!-- spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<!-- 阿里巴巴fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
<!--dbcp -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency> <!-- 辅助 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency> </dependencies> <build> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin> </plugins>
<finalName>${project.artifactId}</finalName>
</build> </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")
private String username; @Column(name = "address")
private String address; @Column(name = "phone")
private String phone; @Column(name = "remark")
private String remark; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public Long getCreated() {
return created;
} public void setCreated(Long created) {
this.created = created;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public String getRemark() {
return remark;
} public void setRemark(String remark) {
this.remark = remark;
} }
package com.ssh.repository; import java.io.Serializable;
import java.util.List; /**
* Created by XRog
* On 2/2/2017.2:28 PM
*/
public interface DomainRepository<T,PK extends Serializable>{
T load(PK id); T get(PK id); List<T> findAll(); void persist(T entity); PK save(T entity); void saveOrUpdate(T entity); void delete(PK id); void flush();
}
package com.ssh.repository; import com.ssh.entity.Person; /**
* Created by XRog
* On 2/2/2017.2:25 PM
*/
public interface PersonRepository extends DomainRepository<Person,Long> {
}
三、建立业务接口及其实现类
package com.ssh.service; import com.ssh.entity.Person; /**
* Created by XRog
* On 2/2/2017.2:39 PM
*/
public interface PersonService {
Long savePerson(); Person getId(Long id); void delete(Long id);
}
package com.ssh.repository.impl; import java.util.List; import javax.persistence.Query; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import com.ssh.entity.Person;
import com.ssh.repository.PersonRepository; /**
* Created by XRog
* On 2/2/2017.2:30 PM
*/
@Repository
public class PersonRepositoryImpl implements PersonRepository { @Autowired
private SessionFactory sessionFactory; private Session getCurrentSession() {
return this.sessionFactory.openSession();
} public Person load(Long id) {
return (Person)getCurrentSession().load(Person.class,id);
} public Person get(Long id) {
return (Person)getCurrentSession().get(Person.class,id);
} public List<Person> findAll() {
Query query = getCurrentSession().createQuery("select * from user");
return query.getResultList();
} public void persist(Person entity) {
getCurrentSession().persist(entity);
} public Long save(Person entity) {
return (Long)getCurrentSession().save(entity);
} public void saveOrUpdate(Person entity) {
getCurrentSession().saveOrUpdate(entity);
} public void delete(Long id) {
Person person = load(id);
getCurrentSession().delete(person);
} public void flush() {
getCurrentSession().flush();
}
}
四、ssh框架相关的xml和properties配置
applicationContext.xml配置如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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 type="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}" /> <!--数据库连接驱动-->
<property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址-->
<property name="user" value="${jdbc.username}" /> <!--用户名-->
<property name="password" value="${jdbc.password}" /> <!--密码-->
<property name="maxPoolSize" value="40" /> <!--最大连接数-->
<property name="minPoolSize" value="1" /> <!--最小连接数-->
<property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接-->
<property name="maxIdleTime" value="20" /> <!--最大空闲时间-->
</bean> <!--配置session工厂-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ssh.entity" />
<property name="hibernateProperties">
<props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
<prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定数据库方言-->
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台显示执行的数据库操作语句-->
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台显示执行的数据哭操作语句(格式)--> </props>
</property> </bean> <!-- 事物管理器配置 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> </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"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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: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层 -->
<context:component-scan base-package="com.ssh.controller"/> <mvc:default-servlet-handler/> <!-- 开启注解 -->
<mvc:annotation-driven /> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
</bean> </beans>
五、Controller
package com.ssh.controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import com.ssh.entity.User;
import com.ssh.service.PersonService;
import com.ssh.service.UserService; /**
* Created by XRog
* On 2/1/2017.12:36 AM
*/
@Controller
public class MainController { @Autowired
private PersonService personService; @Autowired
private UserService userService; @RequestMapping(value = "savePerson", method = RequestMethod.GET)
@ResponseBody
public 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','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文件
<?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"
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</welcome-file>
</welcome-file-list> <!--加载Spring的配置文件到上下文中去-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param> <!-- spring MVC config start-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 此处指向的的是SpringMVC的配置文件 -->
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--配置容器在启动的时候就加载这个servlet并实例化-->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring MVC config end--> <!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 字符集过滤 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
八、启动项目无报错,在浏览器输入对应的requestMapping名字,返回success内容表示成功
spring+springmvc+hibernate整合实例的更多相关文章
- springmvc框架(Spring SpringMVC, Hibernate整合)
直接干货 model 考虑给用户展示什么.关注支撑业务的信息构成.构建成模型. control 调用业务逻辑产生合适的数据以及传递数据给视图用于呈献: view怎样对数据进行布局,以一种优美的方式展示 ...
- 框架篇:Spring+SpringMVC+hibernate整合开发
前言: 最近闲的蛋疼,搭个框架写成博客记录下来,拉通一下之前所学知识,顺带装一下逼. 话不多说,我们直接步入正题. 准备工作: 1/ IntelliJIDEA的安装配置:jdk/tomcat等..(本 ...
- spring+springmvc+hibernate整合遇到的问题
spring+springmvc+hibernate整合遇到的问题2016年10月20日 23:24:03 守望dfdfdf 阅读数:702 标签: ssh学习经历的异常exception异常框架更多 ...
- spring+springmvc+hibernate 整合
三大框架反反复复搭了很多次,虽然每次都能搭起来,但是效率不高.最近重新搭了一次,理顺了思路,整理了需要注意的地方,分享出来. 工具:Eclipse(jdk 1.7) spring和hibernate版 ...
- Spring MVC基础知识整理➣Spring+SpringMVC+Hibernate整合操作数据库
概述 Hibernate是一款优秀的ORM框架,能够连接并操作数据库,包括保存和修改数据.Spring MVC是Java的web框架,能够将Hibernate集成进去,完成数据的CRUD.Hibern ...
- Spring+SpringMvc+Hibernate整合记录
Spring+SpringMvc+Hibernate+Maven整合各大配置文件记录 1.Idea新建的Maven架构 2.Maven的对象模型的内容 <project xmlns=" ...
- 笔记48 Spring+SpringMVC+Hibernate整合
搭建Spring+SpringMVC+Hibernate的框架的思路如下: 1.创建Maven项目,按需映入Maven包依赖. 2.搭建Spring:配置Spring对控件层Bean的注入. 3.搭建 ...
- spring+springmvc+mybaties整合实例
spring+springmvc+mybaties即SSM框架整合在ecpliseee中开发:很么多西都是只有只有自己上手做,才会懂.昨晚熬了很久,才弄出来.也希望对新手有帮助!下面整理一下思路:关键 ...
- spring+springMVC+hibernate整合
首先我们要知道hibernate五大对象:,本实例通过深入的使用这五大对象和spring+springMVC相互结合,体会到框架的好处,提高我们的开发效率 Hibernate有五大核心接口,分别是:S ...
随机推荐
- 学Java的第17天。呃。。。今天有点奇葩
神奇的老师在网上看到狗跳楼的视频然后就想到抛物线问题: 还是 属性和方法的调用: package sklx; public class Dog{ private float v = 30.0f; pr ...
- WindowsPhone8.1 开发技巧
1.调用系统内置滤镜: Windows.ApplicationModel.CameraApplicationManager.ShowInstalledApplicationsUI(); 2.完全退出应 ...
- ssr 之Nuxt.js
ssr:server side rendering(服务端渲染),目的是为了解决单页面应用的 SEO 的问题,对于一般网站影响不大,但是对于论坛类,内容类网站来说是致命的,搜索引擎无法抓取页面相关内容 ...
- CSS--使用伪选择器制作箭头图标
// 使用Transform的属性,组合translate(位移)和rotate(旋转),将生成的小矩形组合成各种箭头样式: HTML <section class="main&quo ...
- Django&Flask区别
Flask Flask 本身只有一个内核,几乎所有的功能都需要用第三方的扩展来实现. Flask 没有默认使用的数据库,默认依赖两个外部库:Jinja2 模板引擎和 WSGI 工具箱(采用的时 Wer ...
- 腾讯X5WebView集成及在移动端中使用
工作中经常涉及H5网页的加载工作,最多使用的就是安卓系统控件WebView,但是当网页内容比较多的时候,需要等待很久才能加载完,加载完后用户才能看到网页中的内容,这样用户需要等很久,体验很差. 那能不 ...
- RabbitMQ延迟消息学习
准备做一个禁言自动解除的功能,立马想到了订单的超时自动解除,刚好最近在看RabbitMQ的实现,于是想用它实现,查询了相关文档发现确实可以实现,动手编写了这篇短文. 准备工作 1.Erlang安装请参 ...
- 使用 PsPing & PaPing 进行 TCP 端口连通性测试
PsPing & PaPing 介绍 通常,我们测试数据包能否通过 IP 协议到达特定主机时,都习惯使用 ping 命令.工作时 ping 向目标主机发送一个 IMCP Echo 请求的数据包 ...
- shell中>/dev/null 2>&1
本文转自http://www.kissyu.org/ 背景 我们经常能在shell脚本中发现>/dev/null 2>&1这样的语句.以前的我并没有去深入地理解这段命令的作用,照搬 ...
- VsCode 的使用
一.简介 VsCode(Visual Studio Code),官网地址:https://code.visualstudio.com/ Visual Studio Code is a lightwei ...