SpringMVC+Spring+Hibernate的小样例
Strusts2+Spring+Hibernate尽管是主流的WEB开发框架,可是SpringMVC有越来越多的人使用了。确实也很好用。用得爽!
这里实现了一个SpringMVC+Spring+Hibernate的小样例。凝视都在代码里面。
项目各包的结构例如以下图:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcWlhbnR1amF2YQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">
1, 首先是pom.xml
<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.0</modelVersion>
<groupId>com.miquan</groupId>
<artifactId>springmvc_spring_hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springmvc_spring_hibernate Maven Webapp</name>
<url>http://maven.apache.org</url> <dependencies>
<!-- expectj -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<!-- dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
</dependencies> <build>
<finalName>springmvc_spring_hibernate</finalName>
</build>
</project>
2, web.xml配置好SpringMVC和Spring
<?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"
id="WebApp_ID" version="3.0"> <!-- Spring配置。 (必须配,要不会找不到bean) -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- spring mvc (系统在启动的时候会依据springmvc-servlet中的配置找到全部的controller并初始化)-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern><!-- 这里不能加* -->
</servlet-mapping> </web-app>
3, SpringMVC的配置——springmvc-servlet.xml(注意命名。相应servlet中的springmvc。命名规则: [<servlet-name>]-servlet.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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"
> <!-- 存在controller的包。注意这里写的是包名,不是类名 -->
<context:component-scan base-package="com.miquan.controller"/>
<mvc:annotation-driven /> <!-- 静态文件 -->
<mvc:resources location="/res/" mapping="/res/**"></mvc:resources> <!-- 跳转文件的前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean> </beans>
4, spring的配置——applicationContext.xml默认是这个名字,而且系统会到WEB-INF文件夹下找这个文件。
须要自己定义名称和文件夹的自己百度一下。
<?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: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-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自己主动扫面注解包 -->
<context:annotation-config />
<context:component-scan base-package="com.miquan.*" /> <!-- 数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/ssh" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean> <!-- 配置sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.miquan.model" /><!-- 实体类的包 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- 会自己主动创表,可是不会自己主动创建数据库,所以要先手动创建数据库。 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean> <!-- 用于注入到GeneralDao中 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 配置事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 开启事务管理注解 -->
<aop:aspectj-autoproxy />
<tx:annotation-driven /> </beans>
5, 实体类。
package com.miquan.model; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;import java.io.Serializable; @Entity
@Table
public class User impements Serializable {
private int id;
private String username;
private String password; public User() {
super();
}
public User(int id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password="
+ password + "]";
}
}
6, controller层。
package com.miquan.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 com.miquan.model.User;
import com.miquan.service.IUserService; @Controller
@RequestMapping(value="/user")
public class UserController {
/**
* 注入userService。 * 假设userService继承了某个接口,
* 这里类型必须是接口IUserService,
* 不能是类UserService,不知道为什么。
*/
@Autowired
private IUserService userService; @RequestMapping(value="/registe", method=RequestMethod.GET)
public String registe() {
User user = new User(0, "小马云", "999");
userService.registe(user);
return "index";
}
}
7, service层。
package com.miquan.service; import com.miquan.model.User; public interface IUserService { public boolean registe(User user); }
package com.miquan.service; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.miquan.dao.IGeneralDao;
import com.miquan.model.User; @Service
public class UserService implements IUserService {
@Autowired
private IGeneralDao generalDao; /*
* 这里要有事务注解。默认readOnly=true,不设置的话会报错。
* insert和update操作都要。 */
@Transactional(readOnly=false)
public boolean registe(User user) {
generalDao.save(user);
return false;
}
}
8, dao层。
package com.miquan.dao; import java.io.Serializable;
import java.util.List; public interface IGeneralDao {
public <T> T findById(Class<T> type, Serializable id); public <T> List<T> findAll(Class<T> type); public void save(Object... entities); public void update(Object... entities); public void saveOrUpdate(Object entity); public void delete(Object... entities); public void deleteById(Class<?> type, Serializable id); public void refresh(Object... entities); public void flush();
}
package com.miquan.dao; import java.io.Serializable;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository; /**
* 这个类将dao成封装成了一个操作类,从网上复制过来的。
*/
@Repository
public class GeneralDao implements IGeneralDao {
/**
* 这个bean里面须要注入sessionFactory,所以把这个bean写在了配置中。
*/
@Autowired
private HibernateTemplate hibernateTemplate; public <T> T findById(Class<T> type, Serializable id) {
return hibernateTemplate.get(type, id);
} public <T> List<T> findAll(Class<T> type) {
return hibernateTemplate.loadAll(type);
} public void save(Object... entities) {
for (Object entity : entities) {
hibernateTemplate.save(entity);
}
} public void saveOrUpdate(Object entity) {
hibernateTemplate.saveOrUpdate(entity);
} public void update(Object... entities) {
for (Object entity : entities) {
hibernateTemplate.update(entity);
}
} public void delete(Object... entities) {
for (Object entity : entities) {
if (entity != null) {
hibernateTemplate.delete(entity);
}
}
} public void deleteById(Class<?> type, Serializable id) {
if (id == null) {
return;
}
Object entity = findById(type, id);
if (entity == null) {
return;
}
delete(entity);
} public void refresh(Object... entities) {
for (Object entity : entities) {
hibernateTemplate.refresh(entity);
}
} public void flush() {
hibernateTemplate.flush();
}
}
9。 測试。
package com.miquan.service; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext; import com.miquan.controller.UserController; public class UserServiceTest {
@Test
public void test() {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"src/main/webapp/WEB-INF/applicationContext.xml");
UserController controller = ctx.getBean(UserController.class);
controller.registe();
}
}
或者部署在tomcat上,在浏览器訪问http://localhost:8080/xx项目/user/registe。
SpringMVC+Spring+Hibernate的小样例的更多相关文章
- Springmvc+Spring+Hibernate搭建方法及实例
Springmvc+Spring+Hibernate搭建方法及实例
- Springmvc+Spring+Hibernate搭建方法
Springmvc+Spring+Hibernate搭建方法及example 前面两篇文章,分别介绍了Springmvc和Spring的搭建方法,本文再搭建hibernate,并建立SSH最基本的代码 ...
- Maven搭建springMVC+spring+hibernate环境
这次不再使用struts2做控制器,采用spring自己的springMVC框架实现. 首先,改写pom.xml文件,不需要struts2的相关jar了. pom.xml <project xm ...
- SpringMVC+Spring+Hibernate整合开发
最近突然想认真研究下java web常用框架,虽然现在一直在用,但实现的整体流程不是很了解,就在网上搜索资料,尝试自己搭建,以下是自己的搭建及测试过程. 一.准备工作: 1/安装并配置java运行环境 ...
- SpringMVC+Spring+Hibernate个人家庭财务管理系统
项目描述 Hi,大家好,今天分享的项目是<个人家庭财务管理系统>,本系统是针对个人家庭内部的财务管理而开发的,大体功能模块如下: 系统管理模块 验证用户登录功能:该功能主要是验证用户登录时 ...
- SpringMVC+Spring+Hibernate+Maven+mysql整合
一.准备工作 1.工具:jdk1.7.0_80(64)+tomcat7.0.68+myeclipse10.6+mysql-5.5.48-win322. 开发环境安装配置.Maven项目创建(参考:ht ...
- Spring DI模式 小样例
今儿跟同事讨论起来spring早期的,通过大篇幅xml的配置演变到今天annotation的过程,然后随手写了个小样例,感觉还不错,贴到这里留个纪念. 样例就是用JAVA API的方式, ...
- spring(一)--spring/springmvc/spring+hibernate(mybatis)配置文件
这篇文章用来总结一下spring,springmvc,spring+mybatis,spring+hibernate的配置文件 1.web.xml 要使用spring,必须在web.xml中定义分发器 ...
- SpringMVC+Spring+Hibernate框架整合原理,作用及使用方法
转自:https://blog.csdn.net/bieleyang/article/details/77862042 SSM框架是spring MVC ,spring和mybatis框架的整合,是标 ...
随机推荐
- JavaScript 中的事件对象(读书笔记思维导图)
在触发 DOM 上的某个事件时,会产生一个事件对象 event,这个对象中包含着所有与事件有关的信息.包括导致事件的元素.事件的类型以及其他与特定事件相关的信息.例如,鼠标操作导致的事件对象中,会包含 ...
- 30天自制操作系统第九天学习笔记(u盘软盘双启动版本)
暑假学习小日本的那本书:30天自制操作系统 qq交流群:122358078 ,更多学习中的问题.资料,群里分享 environment:开发环境:ubuntu 第九天的课程已学完,确实有点不想写 ...
- Android ----制作自己的Vendor
Android源代码使用一个可定制的编译系统来生成 特定的,针对自己硬件平台的Android系统,比方不使用缺省的out/target/prodect/generic文件夹, 本文档简介了这个编译系统 ...
- Ubuntu 8.04下安装DB2方法
參考文献: How-to: Ubuntu 7.10 Server x86 32-bit and DB2 Express-C v9.5 DB2 v9.7 Infomation Center 场景:在IB ...
- 基于CefGlue的桌面应用开发
原文地址:http://johnnyfee.github.io/csharp/2013/12/21/cef-glue/ 前言 如果你想使用WEB技术来开发桌面客户端,并且是想使用的语言也是C#时,那请 ...
- struts2第一个程序的详解(配图)
首先我们在struts2中要写上一个action <packagename="fish"namespace="/test"extends="st ...
- C#反射机制详解(转)
两个现实中的例子:1.B超:大家体检的时候大概都做过B超吧,B超可以透过肚皮探测到你内脏的生理情况.这是如何做到的呢?B超是B型超声波,它可以透过肚皮通过向你体内发射B型超声波,当超声波遇到内脏壁的时 ...
- Resource temporarily unavailable用户的连接数设置的太小
-bash:fork:Resource temporarily unavailable的问题 出现这个问题的原因是linux用户的连接数设置的太小,只要修改max user processes就可 ...
- javaScript滚动新闻
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- 基于HttpClient 4.3的可訪问自签名HTTPS网站的新版工具类
本文出处:http://blog.csdn.net/chaijunkun/article/details/40145685,转载请注明.因为本人不定期会整理相关博文,会对相应内容作出完好.因此强烈建议 ...