ibatis轻松入门
近日,由于公司项目应用开发的逻辑层使用的是iBatis。上网查了些资料,自己写了点demo入门。感觉良好。iBatis实在是比Hibernate很容易入门,贡献出来与各路菜鸟分享(后文附源码),希望得到大神指教。转载请保留本文出处:http://itred.cnblogs.com ; 作者:itRed。
ORM框架中操作数据库的逻辑层中,Hibernate和iBatis相对来说是比较受欢迎的。Hibernate是“全自动”的,能够完全生成SQL语句;而iBatis是“半自动化”的,需要程序员根据自己的应用程序写相应的SQL语句。但是,在实际的开发过程中还是应根据实际情况进行选择。(iBatis的优缺点比较)
优点 | 缺点 |
与JDBC相比减少了很多的代码量;入门简单;架构级性能较强; Sql语句和程序代码的分离;简化项目中的分工; 增强了移植性。 |
Sql语句需要程序员自己写; 参数数量只能一个,但是如果需要多个参数时, 需要将参数打包封装成Map等; |
在进行iBatis应用程序开发之前首先需要对iBatis这个技术有一定的了解。iBatis是apache下的一个开源项目,因为其小巧,上手很快深受程序员的喜爱。iBatis的核心是SqlMap。
本案例将详细介绍iBatis操作MySQL数据库。 利用iBatis对数据库中的记录进行简单的增删改查操作。测试方法main,显示结果到控制台。部分结果直接查看数据库信息。虽然demo比较简单,但是很能起到抛砖引玉的作用。
数据准备:
数据库名称:ibatis
表名称:student
本人数据库中的数据信息:
案例解析及源码:
在正式操作数据库之前需要做一些准备工作,部分备注详见源码注释中:
首先需要导入ibatis的相关jar包,以及连接数据库的驱动jar包;在新建的项目文件下建一个Student的实体Bean。
package com.red; import java.util.Date;
/**
* Student实体类
* @author Red
*
*/
public class Student {
//保证一个无参数方法。反射机制
private int sid=0;
private String sname=null;
private String major=null;
private Date birth=null;
private int score=0; public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() { //重写toString方法,方便控制台显示
String content="sid="+sid+"\tsname:"+sname+"\tmajor:"+major+"\tbirth:"+birth+"\tscore:"+score;
return content;
} }
Student.java
建一个接口以及它的实现类,为了测试方便直接将main方法放到该接口实现类中;
package com.red; import java.util.List;
/**
* 接口
* @author Red
*
*/
public interface IStudentDAO {
public void addStudent(Student student);
public void deleteStudentById(int id);
public void updateStudentById(Student studnet);
public List<Student> queryAllStudent();
public List<Student> queryStudentByName(String name);
public Student queryStudentById(int id);
}
IStudentDAO
package com.red; import java.io.Reader;
import java.sql.SQLException;
import java.util.List; import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder; public class IStudentDAOImpl implements IStudentDAO { private static SqlMapClient sqlMapClient=null;
static{
try{
Reader reader=Resources.getResourceAsReader("com/red/SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}catch (Exception e) {
e.printStackTrace();
}
} public void addStudent(Student student) {
try {
sqlMapClient.insert("insertStudent", student);
} catch (SQLException e) {
e.printStackTrace();
} } public void deleteStudentById(int id) {
try {
sqlMapClient.delete("deleteStudentById",id);
} catch (SQLException e) {
e.printStackTrace();
}
} public List<Student> queryAllStudent() {
List<Student> studentList=null;;
try {
studentList=sqlMapClient.queryForList("selectAllStudent");
} catch (SQLException e) {
e.printStackTrace();
}
return studentList;
} public Student queryStudentById(int id) {
Student student=null;
try {
student=(Student) sqlMapClient.queryForObject("selectStudentById",id);
} catch (SQLException e) {
e.printStackTrace();
}
return student;
} /**
* 模糊查询
*/
public List<Student> queryStudentByName(String name) {
List<Student> studentList=null;
try {
studentList=sqlMapClient.queryForList("selectStudentByName", name);
} catch (SQLException e) {
e.printStackTrace();
}
return studentList;
} public void updateStudentById(Student student) {
try {
sqlMapClient.update("updateStudentById", student);
} catch (SQLException e) {
e.printStackTrace();
} } public static void main(String[] args) {
IStudentDAO dao=new IStudentDAOImpl();
/**
* 查询所有的学生对象*/
for(Student student:dao.queryAllStudent()){//遍历student对象
System.out.println(student);
} /**
* 查询指定id的学生对象
Student student=dao.queryStudentById(1);
System.out.println(student);
//以上两行代码可缩写为:
System.out.println(dao.queryStudentById(1));
*/ /**
* 插入学生对象数据
Student student=new Student();
student.setSid(3);
student.setSname("小明");
student.setMajor("应用化学");
student.setBirth(Date.valueOf("2013-09-09"));
student.setScore(88);
dao.addStudent(student);
*/ /**
* 删除指定id的学生数据
dao.deleteStudentById(1);
*/ /**
* 修改数据对象 Student student=new Student();
student.setSid(3);
student.setSname("朱小明");
student.setMajor("嵌入式开发");
student.setBirth(Date.valueOf("2013-09-09"));
student.setScore(68);
dao.updateStudentById(student);
*/ /**
* 模糊查询 for(Student student:dao.queryStudentByName("t")){
System.out.println(student);
}
*/
}
}
IStudentDAOImpl
建立一个SqlMap.properties的文件,该属性文件主要负责数据库的链接
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ibatis
username=root
password=123456
SqlMap.properies
建立一个SqlMapConfig.xml文件,主要负责ibatis的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQLL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig>
<properties resource="com/red/SqlMap.properties"/>
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driver}"/>
<property name="JDBC.ConnectionURL" value="${url}"/>
<property name="JDBC.Username" value="${username}"/>
<property name="JDBC.Password" value="${password}"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/red/Student.xml"/>
</sqlMapConfig>
SqlMapConfig.xml
建立实体类的映射文件(SQL语句就在其中)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap>
<typeAlias alias="student" type="com.red.Student"/>
<!-- 配置表和实体之间的映射关系 -->
<resultMap class="com.red.Student" id="student">
<result property="sname" column="SNAME"/>
<result property="major" column="MAJOR"/>
<result property="birth" column="BIRTH"/>
<result property="score" column="SCORE"/>
</resultMap> <select id="selectAllStudent" resultClass="student">
SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`
</select> <select id="selectStudentById" parameterClass="int" resultClass="student">
SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`
WHERE SID=#sid#
</select> <insert id="insertStudent" parameterClass="student">
INSERT INTO `ibatis`.`student`(SID,SNAME,MAJOR,BIRTH,SCORE)
values(#sid#,#sname#,#major#,#birth#,#score#)
</insert> <delete id="deleteStudentById" parameterClass="int">
DELETE FROM `ibatis`.`student`
WHERE sid=#sid#
</delete> <update id="updateStudentById" parameterClass="student">
UPDATE `ibatis`.`student` SET
SNAME=#sname#,MAJOR=#major#,BIRTH=#birth#,SCORE=#score#
WHERE sid=#sid#
</update> <select id="selectStudentByName" parameterClass="String" resultClass="student">
SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`
WHERE SNAME LIKE '%$sname$%'
</select>
</sqlMap>
Student.xml
ibatis查询数据库所有数据(重点解析本查询案例,另外的几个操作很简单,源码附注释,很容易看懂。不懂可以Email我。)
public List<Student> queryAllStudent() {
List<Student> studentList=null;;
try {
studentList=sqlMapClient.queryForList("selectAllStudent");
} catch (SQLException e) {
e.printStackTrace();
}
return studentList;
}
Student中的SQL语句:
前几日刚在公司学到的经验,程序员在写SQL语句中的字段和关键字时尽量大写,显得专业,而且提高数据库的查询效率。
<select id="selectAllStudent" resultClass="student">
SELECT SID,SNAME,MAJOR,BIRTH,SCORE FROM `ibatis`.`student`
</select>
Main方法中的测试代码:
IStudentDAO dao=new IStudentDAOImpl();
for(Student student:dao.queryAllStudent()){//遍历student对象
System.out.println(student);
}
运行结果:
iBatis 模糊查询
iBatis 添加数据记录
iBatis 修改数据记录
iBatis 删除数据记录
这些操作都可以依葫芦画瓢,后文附本DEMO的源码,欢迎各位来邮交流学习心得。E-mail: it_red@sina.com
测试时,只需要去除要运行部分的注释。右击测试main方法就可顺利在控制台看到运行结果。
作者:itRed
出处:http://itred.cnblogs.com
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段说明,且在文章明显位置给出原文链接,否则保留追究法律责任的权利。
ibatis轻松入门的更多相关文章
- ibatis 轻松入门
1.总中的配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig ...
- iBatis.net入门指南
iBatis.net入门指南 - 1 - 什么是iBatis.net ? - 3 - iBatis.net的原理 - 3 - 新人指路 - 3 - iBatis.net的优缺点 ...
- Groovy轻松入门——通过与Java的比较,迅速掌握Groovy (更新于2008.10.18)
摘自: http://www.blogjava.net/BlueSUN/archive/2007/03/10/103014.html Groovy轻松入门--通过与Java的比较,迅速掌握Groovy ...
- Groovy轻松入门——搭建Groovy开发环境
摘自: http://www.blogjava.net/BlueSUN/archive/2007/03/17/104391.html Groovy轻松入门--搭建Groovy开发环境 多日来,我发表了 ...
- C++ STL编程轻松入门基础
C++ STL编程轻松入门基础 1 初识STL:解答一些疑问 1.1 一个最关心的问题:什么是STL 1.2 追根溯源:STL的历史 1.3 千丝万缕的联系 1.4 STL的不同实现版本 2 牛刀小试 ...
- Swift轻松入门——基本语法介绍和详细地Demo讲解(利用WebView打开百度、新浪等网页)
转载请务必注明出处(all copyright reserved by iOSGeek) 本文主要分为两个部分,第一部分介绍Swift的基本语法,第二部分讲解一个利用WebView来打开百度.sina ...
- JavaScript面向对象轻松入门之封装(demo by ES5、ES6、TypeScript)
本章默认大家已经看过作者的前一篇文章 <JavaScript面向对象轻松入门之抽象> 为什么要封装? 封装(Encapsulation)就是把对象的内部属性和方法隐藏起来,外部代码访问该对 ...
- asp.net core轻松入门之MVC中Options读取配置文件
接上一篇中讲到利用Bind方法读取配置文件 ASP.NET Core轻松入门Bind读取配置文件到C#实例 那么在这篇文章中,我将在上一篇文章的基础上,利用Options方法读取配置文件 首先注册MV ...
- AngularJs轻松入门
AngularJs轻松入门系列博文:http://blog.csdn.net/column/details/angular.html AngularJs轻松入门(一)创建第一个应用 AngularJs ...
随机推荐
- C++ 非阻塞套接字的使用 (3)
异步非阻塞套接字避免了死循环的接收问题,但是软件用起来体验还是很差.究其原因,软件在指令的发送.接收上, 采取了一种不合理的方式:在指令的发送后,立刻调用接收函数,等待回令. 若是采用同步阻塞套接字, ...
- 关于NPOI导入导出
http://www.360doc.com/content/14/0110/16/432969_344152497.shtml NPOI汇入Excel仅支持2007版本以内: [HttpPost] p ...
- 【leetcode】Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...
- 开源库Magicodes.ECharts使用教程
目录 1 概要 2 2 Magicodes.ECharts工作原理 3 2.1 架构说明 3 2.1.1 Axis 4 2.1.2 CommonD ...
- 通过Measure & Arrange实现UWP瀑布流布局
简介 在以XAML为主的控件布局体系中,有用于完成布局的核心步骤,分别是measure和arrange.继承体系中由UIElement类提供Measure和Arrange方法,并由其子类Framewo ...
- 消息中间件与JMS标准
初识消息中间件 维基百科上对于消息中间件的定义是"Message-oriented middleware(MOM) is software infrastructure focused on ...
- 走进AngularJs(八) ng的路由机制
在谈路由机制前有必要先提一下现在比较流行的单页面应用,就是所谓的single page APP.为了实现无刷新的视图切换,我们通常会用ajax请求从后台取数据,然后套上HTML模板渲染在页面上,然而a ...
- HTTP学习笔记(五)
目前,市场上流行有很多web服务器软件,每种服务器都有自己的特点.我们在开发的过程中,经常要和它们打交道,所以了解它们的工作原理也是很重要的. 几款比较流行的服务器 它们会做些什么? 第三篇中有这样的 ...
- 使用IPostBackEventHandler让JavaScript“调用”回传事件
在由ASP.NET所谓前台调用后台.后台调用前台想到HTTP——实践篇(二)通过自己模拟HTML标签事件与服务器交互,讲了ASP.NET的服务器控件是怎么render成HTML后市怎么“调用”后台方法 ...
- MVVM架构~Knockoutjs系列之text,value,attr,visible,with的数据绑定
返回目录 Knockoutjs是微软mvc4里一个新东西,用这在MVC环境里实现MVVM,小微这次没有大张旗鼓,而是愉愉的为我们开发者嵌入了一个实现MVVM的插件,这下面的几篇文章中,我和大家将一起去 ...