ibatis学习笔记

STM32使用HAL库实现ModbusRTU主站核心要点 深入解析STM32如何利用HAL库高效实现ModbusRTU主站通信,重点讲解串口配置、定时控制与modbusrtu协议帧的构建方法,提升嵌入式通信稳定性与实时性。 阅读详情

本文是iBatis SQL MapsDeveloper Guide的中文版学习笔记,该文档中文名叫《iBATIS SQL Maps 开发指南》,参照文档,一边做例子

下面记录下学习过程,方便记忆

注:文档是ibatis2.0,但下面用的包是ibatis2.3,现在ibatis已经改为mybatis,版本已经是3.x

ibatis确实好小巧,文档也比较详细,也比较容易学习,看一天就使用得差不多了


如果你还在用JDBC进行编程,那么建议你学一下ibatis,ibatis小巧灵活,开发ibatis的目的就是提供一个简洁的架构,能够用20%的代码实现80%JDBC的功能。如果你在学hibernate、jdo、Toplink及JPA的话,那就另当别论,当然还是建议看一下ibatis.


一、导入jar包

二、配置文件

三、javaBean对象

四、SQLMap XML映射文件

五、代码测试

六、总结



一、导入jar包

本次使用的版本是ibatis2.3,使用的ide工具是eclipse4.3

classes12.jar
commons-logging-1.0.4.jar
ibatis-sqlmap-2.3.0.jar

只须导入 三个包即可,一个是数据库jar,一个是ibatis包,另一个是ibatis依赖包


二、配置文件

SQLMap使用XML配置文件统一配置不同的属性,包括DataSource的详细配置信息,SQLMap和其他可选属性,如线程管理等。


SqlMapConfigExample.properties

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521/orcl
username=colin
password=colin

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig 
PUBLIC "-//iBATIS.com//DTD SQL Map Config2.0//EN" 
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<!-- Alwaysensure touse the correct XMLheader as above! -->
<sqlMapConfig>
	<!-- Theproperties (name=value) inthe file specifiedhere canbeusedplaceholders 
		inthis config file (e.g. “${driver}”. The file is relativeto the classpath 
		and is completelyoptional. -->
	<properties resource="SqlMapConfigExample.properties" />
	<!-- //可以采用固定路径 -->
	<!-- <properties url="file:///c:/config/my.properties" /> -->

	<!-- These settingscontrol SqlMapClientconfiguration details, primarilytodo 
		withtransaction management. Theyareall optional (moredetail later in thisdocument). -->
	<settings cacheModelsEnabled="true" enhancementEnabled="true"
		lazyLoadingEnabled="true" maxRequests="32" maxSessions="10"
		maxTransactions="5" useStatementNamespaces="true" />

	<!-- Typealiases allowyoutouse a shorter name for longfullyqualifiedclass 
		names. -->
	<typeAlias alias="Student" type="com.diyjava.entity.Student" />

	<!-- Configureadatasource to use withthisSQL Map using SimpleDataSource. 
		Notice the use ofthe properties fromthe above resource -->
	<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}" />
			<property name="JDBC.DefaultAutoCommit" value="true" />
			<property name="Pool.MaximumActiveConnections" value="10" />
			<property name="Pool.MaximumIdleConnections" value="5" />
			<property name="Pool.MaximumCheckoutTime" value="120000" />
			<property name="Pool.TimeToWait" value="500" />
			<property name="Pool.PingQuery" value="select1from ACCOUNT" />
			<property name="Pool.PingEnabled" value="false" />
			<property name="Pool.PingConnectionsOlderThan" value="1" />
			<property name="Pool.PingConnectionsNotUsedFor" value="1" />
		</dataSource>
	</transactionManager>

	<!-- Identifyall SQL Map XML files to be loadedbythis SQLmap.Notice the 
		paths are relativetothe classpath.Fornow, we onlyhaveone… -->
	<sqlMap resource="com/diyjava/entity/student.xml" />

</sqlMapConfig>

<setting>元素
<setting>元素用于配置和优化SqlMapClient实例的各选项

属性说明默认值
maxRequests     同时执行SQL语句的最大线程数512
maxSessions     同一时间内活动的最大session数128
maxTransactions    同时进入SqlMapClient.startTransaction()的最大线程数。32
cacheModelsEnabled     全局性地启用或禁用SqlMapClient 的所有缓存modelTRUE
lazyLoadingEnabled     全局性地启用或禁用SqlMapClient的所有延迟加载。TRUE
enhancementEnabled     全局性地启用或禁用运行时字节码增强,以优化访问Java Bean属性的性能,同时优化延迟加载的性能FALSE
useStatementNamespaces     如果启用本属性,必须使用全限定名来引用mapped statementFALSE


<typeAlias>元素
<typeAlias>元素让您为一个通常较长的、全限定类名指定一个较短的别名
例如:<typeAliasalias="Student" type="com.diyjava.entity.Student"/>

在SQLMap配置文件预定义了几个别名

事务管理器别名Data Source Factory别名
JDBC SIMPLE 
JTA DBCP 
EXTERNALJNDI

<sqlMap>
<sqlMap>元素用于包括SQLMap映射文件和其他的SQLMap 配置文件。每个
SqlMapClient 对象使用的所有SQLMap映射文件都要在此声明。映射文件作为stream resource从类路径或URL读入。

类路径导入

<sqlMap resource="com/diyjava/entity/student.xml" />

或url导入

<sqlMap url="file:///C:/MyTest/src/com/diyjava/entity/student.xml" />


三、javaBean对象

Student.java

package com.diyjava.entity;

import java.io.Serializable;

/**
 * 学生对象
 * 
 * @author linchd
 * 
 */
public class Student implements Serializable {
	private static final long serialVersionUID = 2909148295648618241L;
	/** 标识 */
	private int id;
	/** 姓名 */
	private String name;
	/** 年龄 */
	private int age;
	/** 地址 */
	private String address;

	public Student() {
		super();
	}

	public Student(String name, int age, String address) {
		super();
		this.name = name;
		this.age = age;
		this.address = address;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age
				+ ", address=" + address + "]";
	}
}


这就是一个普通的javaBean对象,没有啥好说,记得在oracle数据库创建表Student时,创建序列

-- Create sequence
create sequence STUDENTSEQUENCE
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
cache 20;


create table STUDENT
(
  student_id      NUMBER(6) primary key not null,
  student_name    VARCHAR2(20) not null,
  student_age     NUMBER(3),
  student_address VARCHAR2(100)
);


四、SQLMap XML映射文件

student.xml

<?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 namespace="public_student_tbl">
	<!-- 查询结果,Student对象Bean和数据表的字段相对应 -->
	<resultMap id="studentResult" class="com.diyjava.entity.Student">
		<result column="STUDENT_ID" property="id" jdbcType="NUMERIC" />
		<result column="STUDENT_NAME" property="name" jdbcType="VARCHAR" />
		<result column="STUDENT_AGE" property="age" jdbcType="NUMERIC" />
		<result column="STUDENT_ADDRESS" property="address" jdbcType="VARCHAR" />
	</resultMap>

	<!-- 根据标识进行查询 -->
	<select id="getStudent" parameterClass="Student" resultMap="studentResult">
		select * from STUDENT
		where
		STUDENT_ID = #id#
	</select>
	<!-- 添加记录 -->
	<insert id="insertStudent" parameterClass="com.diyjava.entity.Student">
		<!-- 由于用的数据库是oracle,使用序列STUDENTSEQUENCE -->
		<selectKey resultClass="int" keyProperty="id">
			SELECT
			STUDENTSEQUENCE.NEXTVAL AS ID FROM DUAL
		</selectKey>
		insert into Student(STUDENT_ID, STUDENT_NAME, STUDENT_AGE,
		STUDENT_ADDRESS) values (#id#, #name#, #age#, #address#)
	</insert>
</sqlMap>



注:
SQLMap的名称是全局性的,在所有的SQLMap文件中名称必须是唯一的。所以这里设置

namespace="public_student_tbl"
还启用namespace
useStatementNamespaces="true"

五、代码测试


SqlMapUtil.java

package com.diyjava.util;

import java.io.IOException;
import java.io.Reader;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

/**
 * 获取SqlMapClient
 * @author linchd
 *
 */
public class SqlMapUtil {

	public static SqlMapClient getSqlMapClient() {
		SqlMapClient client = null;
		String resource = "SqlMapConfig.xml";
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(resource);
		} catch (IOException e) {
			e.printStackTrace();
		}
		client = SqlMapClientBuilder.buildSqlMapClient(reader);
		return client;
	}

}


StudentDao.java

package com.diyjava.dao;

import java.sql.SQLException;

import com.diyjava.entity.Student;
import com.diyjava.util.SqlMapUtil;
import com.ibatis.sqlmap.client.SqlMapClient;

/**
 * dao层 <br/>
 * sql语句都是使用namespace+id形式,如果不使用namespace,
 * 请在SqlMapConfig.xml中,把settings里的属性值useStatementNamespaces设为false
 * 
 * @author linchd
 * 
 */
public class StudentDao {
    private SqlMapClient client = null;

    public StudentDao() {
        client = SqlMapUtil.getSqlMapClient();
    }

    /**
     * 查询 查找标识 为2的记录
     * 
     * @throws SQLException
     */
    private void getStudent() throws SQLException {
        client.startTransaction();
        Student key = new Student();
        key.setId(2);

        Student student = (Student) client.queryForObject(
                "public_student_tbl.getStudent", key);

        client.commitTransaction();
        System.out.println(student);
    }

    /**
     * 添加记录
     * 
     * @throws SQLException
     */
    public void insertStudent() throws SQLException {
        client.startTransaction();
        Student key = new Student();
        key.setName("diandian");
        key.setAge(18);
        key.setAddress("xxxx");
        
        //添加成功,返回标识
        int student_id = (int) client.insert("public_student_tbl.insertStudent", key);

        client.commitTransaction();
        System.out.println(student_id);
    }

    /**
     * 进行测试,仅仅是为了学习,没有使用junit进行test<br/>
     * 
     * 运行就可以看结果 啦,方便
     * 
     * @param args
     */
    public static void main(String[] args) {
        StudentDao dao = new StudentDao();
        try {
            dao.insertStudent();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}



六、总结

作为一名技术男(真正的说法,其实是一位不合格的技术男),平时半天也崩不出一句话,真的没有啥好总结,如果真的要总结,通俗地说:用过的都说好,Ibatis,您值得一试。主要您会Sql,就不怕学不会Ibatis。

下面提供源码,大家可以去看看


代码下载


手把手带你搞懂电压跌落测试DIP 砖一用4分钟时间手把手带你搞懂电压跌落测试DIP,希望对你有用~ 阅读详情

相关推荐

ibatis工程依赖的jar包

构建ibatis工程必须的两个jar包,分别为:ibatis-2.3.4.726.jar和mysql-connector-java-5.1.6-bin.jar。

ibatis的引入——maven搭建spring mvc+ibatis项目(三)

1、spring中引入ibatis配置文件,上章已有相关配置,这里再补充重点的。 [code="xml"] classpath:config/ibatis.xml [/code] 2、config/ibatis.xml的内容: [code="xml"] [/code] 3、config/ibatis_...

A07151102108的专栏 1226

ibatis 学习笔记

ibatis 学习笔记 ibatis 学习笔记 ibatis 学习笔记 ibatis 学习笔记 ibatis 学习笔记 ibatis 学习笔记 ibatis 学习笔记 ibatis 学习笔记

一个完整的springboot项目所需要导入的依赖合集(方便查找)

一、springboot启动类依赖: 二、springboot测试类依赖: 三、mybatis-plus依赖: 四、lombok依赖(用来简化对类的操作包括:set、get以及构造函数等,只需要 一个注解) 导入lombok依赖后还需要进行一步操作,下载lombok插件,方法:点击File—>Setting—>Plugins然后再搜索框搜索Lombok,安装插件即可。五、mysql连接所需要的依赖: 导入了mysql依赖后需要连接数据库,在application.yaml配置文件中配置连

qq_56728342的博客 4万+

ibatis学习笔记(完整)

1.Ibatis是开源软件组织Apache推出的一种轻量级的对象关系映射(ORM)框架,和Hibernate、Toplink等在java编程的对象持久化方面深受开发人员欢迎。 对象关系映射(ORM):简单原理是通过面向对象方式操作关系型数据库,目前存储数据最常用最流行的工具是关系型数据库,其操作方式是通过SQL语句操作数据库的表,但是对于Java面向对象编程语言中,所有的操作对象都...

weixin_30300225的博客 279

ibatis学习笔记ibatis学习笔记

ibatis学习笔记ibatis学习笔记

yangle5610的博客 197

ibatis学习笔记之一环境搭建

ibatis学习笔记之一环境搭建 参考文档 http://www.cnblogs.com/ycxyyzw/archive/2012/10/13/2722567.html 视频讲解 http://360kan.youku.com/kan/play?md5=f0d364eb83354271&site=youku&title=ibatis%E8%A7%86%E9%A2%91%E6%95%99%E

云智禅师的专栏 628

ibatis学习笔记(一)

ibatis学习笔记(一)

congine_mcfeng的专栏 172

IBATIS学习笔记支 - SQL Maps

IBATIS学习笔记支 - SQL Maps[url]http://zhuyuehua.iteye.com/blog/1048369[/url]

iteye_763的博客 233

iBatis学习笔记

配置:http://www.cnblogs.com/ycxyyzw/archive/2012/10/13/2722567.html Employee.xml文件 <!--创建插入操作--> <sqlMap namespace="Employee"> <insert id="insert" parameterClass="Employee"> insert into EMPLOYEE(first

h 414

IBatis.Net学习笔记系列文章

IBatis.Net是一个比较易用的ORM框架,使用起来较为方便、灵活。在此记录我学习的过程,作为自己的一个总结。(本系列会不断更新)1、IBatis.Net学习笔记一:开篇 2IBatis.Net学习笔记二:下载、编译、运行NPetShop 3IBatis.Net学习笔记三:两种常用的DAO 4、IBatis.Net学习笔记四:数据库的缓存模式 5、IBatis.Net学习笔记五:常用...

weixin_30412577的博客 71

iBATIS系统学习笔记

iBATIS高级特性,包括高速缓存,DAO进阶,iBATIS扩展

啊昕的博客 1142

iBATIS系统学习笔记

基础知识,涉及到安装和配置,已映射语句,非查询语句,高级查询技术,事务,动态SQL

啊昕的博客 1499

spring+ibatis整合之jar包引入配置篇

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33843409的博客 681

maven中org.apache.ibatis.*导入出现异常的解决方案

解决maven中拷贝外部文件但出现部分包无法导入的问题 项目右键选中 maven reimport 用此方法是解决了org.apache.ibatis.*导入问题

weixin_44248411的博客 3011

依赖包冲突启动报错:An attempt was made to call the method

今天,maven中添加了一个依赖,添加完启动不起了,内心崩溃!!! 查了一下,原来是依赖包冲突了,按照之前的步骤,排除冲突! 开搞,maven插件右击子项目,再点击 show dependenices,如下图,1查看冲突地方,2依赖图放大. 排除后发现,guava与另一个依赖包也存在冲突,最后,直接指定子项目 使用的版本,搞定!!! <dependency> <groupId>com.google.guava</groupId> &.

qq_34910843的博客 1万+

ASP.Net MVC4 的工程中引入IBatis步骤

在C#开发的 ASP.Net MVC4 的工程中引入IBatis步骤: 1,在工程的DLL依赖中加入IBatis相关的DLL,即 IBatisNet.Common.dll, IBatisNet.DataAccess.dll, IBatisNet.DataMapper.dll 这三个DLL; 2,对应数据库驱动需要事先安装好; 3,在工程项目下建立IBatis配置文件,其中应包含数据库连

shenzhenNBA的专栏 3912

Mybatis依赖引入及其配置

Mybatis使用注意事项(1),关于环境之间的配置 Maven工程pom.xml需要引入的Mybatis有关依赖 <!-- Mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version&gt

若白的博客 1万+

S7 F ConfigurationPack V5.5 sp13 下载

SIMATIC S7 F ConfigurationPack 是在由Siemens AG开发类别 Home & Hobby Shareware 软件。F-Configuration 工具是 S7-Distributed Safety 和 S7 F-Systems 的一部分 。它为用户提供了用于 Step 7 V5 Hardware Config 的故障安全模块。

上一篇: spring3.1 mvc入门讲解
下一篇: spring国际化小结
linchunda
博客等级 码龄19年 21粉丝 62原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值