您的位置:首页 > 编程语言 > Java开发

Spring3.13 + Mybatis3.1.1 简单例子

2013-06-09 17:15 411 查看
零 【概述】

这是一个简单的Mybatis 与Spring Mvc 集成的例子。

查询是两个表的联合查询。

也添加了Spring的事务管理配置

每一个MyBatis的应用程序都以一个SqlSessionFactory 对象的实例为核心。

SqlSessionFactory 对 象的 实例 可以 通 过SqlSessionFactoryBuilder 对 象 来获 得 。

SqlSessionFactoryBuilder对象可以从XML配置文件,或从Configuration类的习惯准备的实例中构建SqlSessionFactory对象。

一 【起源】

因为自己对Mybatis了解的太少,深感惶恐不安。于是乎,通过一个简单的例子来加深对Mybatis的理解。

优点&为什么要用Mybatis

1 开源

2 简单

Mybatis被广泛认为是最简单的一种持久化框架

简洁的代码和简单的配置使得使用iBATIS所需的代码量可以减少到了相应JDBC代码的62%。

3 易维护

因为
iBatis 的 sql 都保存到单独的文件中。

4
运行效率

在不考虑
cache 的情况下,Mybatis应该会比hibernate 快一些或者很多。



需要手写sql,可以进行细粒度的优化。

与Hibernate相比较:

Hibernate功能强大,O/R映射能力强,学习门槛高。

Hibernate现在已经是主流O/R Mapping框架,从文档的丰富性,产品的完善性,版本的开发速度都要强于Mybatis。

Hibernate对数据库结构提供了较为完整的封装,Hibernate的O/R Mapping实现了POJO 和数据库表之间的映射,以及SQL 的自动生成和执行。

Mybatis半ORM,并不会为程序员在运行期自动生成SQL 执行,需要程序员自己手写sql。

二 【结构及用到的jar包】



jar包




 【配置】

3.1
web.xml



3.2 Spring 相关配置

3.2.1 applicationContext.xml



数据库的用户名 密码 地址是配置在这个文件里的。

注意userService 是被注释掉了,不然会报错。

datasource用了两种配置方式 jdbc 以及 proxool

在这里引用下网上对连接池的评论

目前常用的连接池有:C3P0、DBCP、Proxool

网上的评价是:

C3P0比较耗费资源,效率方面可能要低一点。

DBCP在实践中存在BUG,在某些种情会产生很多空连接不能释放,Hibernate3.0已经放弃了对其的支持。

Proxool的负面评价较少,现在比较推荐它,而且它还提供即时监控连接池状态的功能,便于发现连接泄漏的情况。

3.2.2 Spring MVC 配置

spring-servlet.xml

图:



3.3Mybatis配置

3.3.1 配置MyBatis配置文件--mybatis-config.xml



3.3.2
Sql Mapper 文件

IUserService.xml



可以看到是两张表
做了 联合查询的


【Service层】

数据层的接口,这里我觉着放到service包里更合适



接口实现类 UserServiceImp




【Controller】

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.servlet.ModelAndView;

import com.sm.domain.Employee;
import com.sm.service.IUserService;

@Controller
@RequestMapping("/sm.do")
public class SmDemoController {
//	使用注解实现自动装配 不需要再写get set方法以及在context中配置bean
@Autowired
private IUserService service;

@RequestMapping(method = RequestMethod.GET)
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response){
ModelAndView view = null;
List list = new ArrayList();

try{
list = service.getAllEmployee();
view = new ModelAndView("/list");
request.setAttribute("list", list);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
request.setAttribute("error", "系统错误!");
request.setAttribute("exception", e);
}
return view;
}

@RequestMapping(params = "method=listUserById")
public ModelAndView listUserById(HttpServletRequest request,
HttpServletResponse response){
ModelAndView view = null;
Employee employee = new Employee();

String idStr = request.getParameter("id");
int userId = Integer.parseInt(idStr);

try{
employee = service.getEmployeeById(userId);
view = new ModelAndView("/listById");
request.setAttribute("employee", employee);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
request.setAttribute("error", "系统错误!");
request.setAttribute("exception", e);
}

return view;

}

}



【View 层】

列表界面



明细页面




【问题及解决】

1 Caused
by: java.lang.ClassNotFoundException: org.mybatis.spring.SqlSessionFactoryBean

缺少jar包 
http://code.google.com/p/mybatis/ 下载mybatis-spring-1.0.0.jar



org.springframework.beans.factory.BeanCreationException: 

Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: 

Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: 

Failed to parse config resource: class path resource [mybatis-config.xml]; 

nested exception is org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. 

Cause: java.lang.RuntimeException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: 

Error resolving class . Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'employResult'.  

Cause: java.lang.ClassNotFoundException: Cannot find class: employResult

修改

IUserService.xml

<select id="getEmployeeById" parameterType="int" resultType="employResult">

将resultType 修改为 resultMap="employResult"

3

严重:
Couldn't load class ${jdbc.driverClassName}

在applicationContext.xml 中增加

<context:property-placeholder location="classpath:jdbc.properties" />

4

java.lang.ClassNotFoundException:
javax.servlet.jsp.jstl.core.Config

添加jstl.jar


【鸣谢】

MyBatis
Reference Document
http://mybatis.github.io/mybatis-3/index.html http://daoxiaozhang.iteye.com/blog/1566195
另外也参考了我的另外一篇博文
http://blog.csdn.net/bruce_sky/article/details/8549116
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: