Maven+Spring+SpringMVC+Hibernate+Mysql的简单整合(入门级),实现数据库的增删查改。Maven管理项目,统一开发规范和工具、统一管理Jar包。Spring轻量级的Java开发框架、控制反转IOC和依赖注入DI来管理对象依赖关系.、面向切面编程AOP来管理事物等。SpringMVC轻量级Web框架,使用MVC架构思想对web层进行解耦,简化开发。Hibernate全自动ORM(对象关系映射)框架,是持久层的框架,使我们采用对象化的思维操作关系型数据库。Mysql关系型数据库。
File-->New-->other..-->Maven Project-->Next-->Next
选择Maven的webapp项目。
填写 Group id、Artifact Id、Version、Package ,点击Finish完成。
** 注:groupId、artifactId、version三个元素生成了一个Maven项目的基本坐标**
使用Maven管理项目,统一开发规范和工具,统一管理jar包。
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.chronosgroupId>
<artifactId>msshartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>mssh Maven Webappname>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-expressionartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.9version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-coreartifactId>
<version>4.3.8.Finalversion>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-entitymanagerartifactId>
<version>4.3.8.Finalversion>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-ehcacheartifactId>
<version>4.3.8.Finalversion>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.18version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.39version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.12version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-apiartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.6version>
dependency>
dependencies>
<build>
<finalName>msshfinalName>
build>
project>
数据库的相关配置,包括数据库驱动、链接url、用户名、密码、数据库名称,连接的初始化大小、最小、最大、等待时间,hibernate的方言dialect等属性。
##mysql数据库
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mssh?useUnicode=true&characterEncoding=UTF-8
user=root
password=root
dbname=mssh
##oracle数据库
#driverClass=oracle.jdbc.OracleDriver
#url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#username=ptest
#password=password
#dbname=orcl
#配置初始化大小、最小、最大 、等待时间
initialSize=1
minIdle=1
maxIdle=20
maxActive=100
maxWait=60000
##hiberate属性
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
Spring和Hibernate的相关配置、包括自动扫描、配置数据库datasource、配置sessionFactory、配置事务等。
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="classpath:config.properties"/>
<context:component-scan base-package="com.chronos.mssh">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${driverClass}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${password}" />
<property name="initialSize" value="${initialSize}" />
<property name="minIdle" value="${minIdle}" />
<property name="maxActive" value="${maxActive}" />
<property name="maxWait" value="${maxWait}" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<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>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}prop>
<prop key="current_session_context_class">threadprop>
<prop key="hibernate.connection.driver_class" >${driverClass}prop>
props>
property>
<property name="mappingLocations">
<value>classpath:/com/chronos/mssh/model/*.hbm.xmlvalue>
property>
bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory">property>
bean>
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="aopPointcut" expression="execution(* com.chronos.mssh.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="aopPointcut" advice-ref="transactionAdvice"/>
aop:config>
beans>
###Hibernate 映射方式
<property name="packagesToScan">
<list>
<value>com.chronos.mssh.modelvalue>
list>
property>
<property name="mappingLocations"> <value>classpath:/com/chronos/mssh/model/*.hbm.xmlvalue>
property>
建议采用映射文件的方式。
<tx:annotation-driven transaction-manager="transactionManager"/>
拦截方式配置事务
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="aopPointcut" expression="execution(* com.chronos.mssh.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="aopPointcut" advice-ref="transactionAdvice"/>
aop:config>
```
** 建议采用拦截方式配置事务。**
Spring MVC相关配置,配置扫描Controller、开启自动扫描、视图解析配置等。
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.chronos.mssh.controller">context:component-scan>
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
bean>
beans>
web项目的相关配置。包括配置contextConfigLocation定义要装入的配置文件(如spring和Hibernate配置文件),配置前端控制器(DispatcherServlet). 配置字符集过滤器(encodingFilter)、默认访问页面、错误访问页面等。
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/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>msshdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>openSessionInViewFilterfilter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilterfilter-class>
<init-param>
<param-name>singleSessionparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>sessionFactoryBeanparam-name>
<param-value>sessionFactoryparam-value>
init-param>
filter>
<servlet>
<servlet-name>springMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springMVCservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
创建Contoller层、Service层、dao层以及实体model和映射文件
创建实体和映射文件 或 注解,运行程序后,HIbernate会自动在数据库创建表。
package com.chronos.mssh.model;
import java.util.List;
/**
* 用户实体
*
* @author chronos
* @date 2017年4月26日 下午1:05:20
*/
public class User {
private Integer id; //id,主键
private String userName; //用户名称
private String password; //登录密码
private String nickName; //昵称
private Integer age; //年龄
private boolean sex; //性别
private String signature; //个性签名
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
xml version="1.0"?>
<hibernate-mapping >
<class name="com.chronos.mssh.model.User" table="user">
<id name="id" column="id" type="integer">
<generator class="native" />
id>
<property name="userName" column="username" type="string"/>
<property name="password" column="password" type="string"/>
<property name="nickName" column="nickname" type="string"/>
<property name="age" column="age" type="integer"/>
<property name="sex" column="sex" type="boolean"/>
<property name="signature" column="signature" type="string"/>
class>
hibernate-mapping>
package com.chronos.mssh.model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GeneratorType;
/**
* 用户实体
*
* @author chronos
* @date 2017年4月26日 下午1:05:20
*/
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id; //id,主键
private String userName; //用户名称
private String password; //登录密码
private String nickName; //昵称
private Integer age; //年龄
private boolean sex; //性别
private String signature; //个性签名
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.chronos.mssh.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.chronos.mssh.model.User;
import com.chronos.mssh.service.IUserService;
/**
* 用户controller层
*
* @author chronos
* @date 2017年4月26日 下午1:41:11
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/addUser")
private String addUser(){
User user = new User();
user.setUserName("chronos");
user.setPassword("123456");
user.setAge(1);
user.setSex(true);
user.setSignature("代码改变世界!");
user.setNickName("chronos");
this.userService.addUser(user);
return "welcome";
}
public IUserService getUserService() {
return userService;
}
public void setUserService(IUserService userService) {
this.userService = userService;
}
}
注解:
package com.chronos.mssh.service;
import com.chronos.mssh.model.User;
/**
* 用户service层接口
*
* @author chronos
* @date 2017年4月26日 下午1:42:16
*/
public interface IUserService {
/**
* 添加用户
*
* @param user
*/
void addUser(User user);
}
package com.chronos.mssh.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chronos.mssh.dao.IUserDao;
import com.chronos.mssh.model.User;
import com.chronos.mssh.service.IUserService;
/**
* 用户service层实现
*
* @author chronos
* @date 2017年4月26日 下午1:42:34
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public void addUser(User user) {
this.userDao.addUser(user);
}
public IUserDao getUserDao() {
return userDao;
}
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
}
注解
package com.chronos.mssh.dao;
import com.chronos.mssh.model.User;
/**
* 用户dao层接口
*
* @author chronos
* @date 2017年4月26日 下午1:41:37
*/
public interface IUserDao {
/**
* 添加用户
*
* @param user
*/
void addUser(User user);
}
package com.chronos.mssh.dao.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.chronos.mssh.dao.IUserDao;
import com.chronos.mssh.model.User;
/**
* 用户dao层实现
*
* @author chronos
* @date 2017年4月26日 下午1:41:58
*/
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public void addUser(User user) {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
session.save(user);
}
}
注解:
** session获取方式**
Session session = sessionFactory.getCurrentSession();
// getCurrentSession和当前线程绑定,在事务结束后会自动关闭
必须开启事务,同时配置Hibernate
"current_session_context_class">thread
//jta 、 thread 常用 , custom、managed 少用,
//thread使用connection 单数据库连接管理事务
//jta (Java transaction api) Java 分布式事务管理 (多数据库访问),jta 由中间件提供(JBoss WebLogic 等, 但是tomcat 不支持)
Session session = sessionFactory.openSession();
//openSession没有绑定当前线程,所以,使用完后必须关闭
session.close();
** 建议使用getCuttentSession()方法获取。**
打开Nvaicat 软件,连接mysql,创建新的数据库mssh
可以创建表,也可以不创建表,** Hibernate会根据实体自动创建表**。
将项目部署在Tomcat中运行
在浏览器访问 http://localhost:8080/mssh/user/addUser
以上是Maven+Spring+SpringMVC+Hibernate+Mysql的简单整合(入门级),实现数据库的增删查改。