ibatis的初相识

简介:

iBatis 是apache 的一个开源项目,一个O/R Mapping 解决方案,iBatis 最大的特点就是小巧,上手很快。如果不需要太多复杂的功能,iBatis 是能够满足你的要求又足够灵活的最简单的解决方案,现在的iBatis 已经改名为Mybatis 了。

官网为:http://www.mybatis.org/

搭建iBatis 开发环境:

1 、导入相关的jar 包,ibatis-2.3.0.677.jar

2 、编写配置文件:

Jdbc 连接的属性文件

总配置文件, SqlMapConfig.xml

关于每个实体的映射文件(Map 文件)

DEMO:

Jdbc 连接的属性文件

SqlMap.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myam_fts
username=root
password=sba
注意:在配置的时候键值对后面不能有空白,之前在driver=com.mysql.jdbc.Driver  后面有空白,导致程序一直java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
总配置文件, SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" 
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- 引用JDBC属性的配置文件 -->
<properties resource="SqlMap.properties"/>
<!-- 使用JDBC的事务管理 -->
<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="ibatis/entity/SeqNo.xml"/>
</sqlMapConfig>
关于每个实体的映射文件(Map 文件)
SeqNo.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>
	<!-- 通过typeAlias使得我们在下面使用Student实体类的时候不需要写包名 -->
	<typeAlias alias="SeqNo" type="ibatis.entity.SeqNo" />
	<!-- 这样以后改了sql,就不需要去改java代码了 -->
	<!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->
	<select id="selectSeqNoById" parameterClass="String" resultClass="SeqNo">
		select * from seq_no where compID=#compID#
	</select>
</sqlMap>
使用:MainTest.java
package ibatis.test;

import ibatis.entity.SeqNo;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;

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

public class MainTest {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws SQLException 
	 */
	public static void main(String[] args) throws IOException, SQLException {
		// TODO Auto-generated method stub
		Reader reader = Resources
				.getResourceAsReader("SqlMapConfig.xml");
		SqlMapClient sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
		reader.close();
		SeqNo seqNo = (SeqNo) sqlMapClient.queryForObject( 
				"selectSeqNoById", "1988");
		System.out.println(seqNo.getCompID());
		System.out.println(seqNo.getBaseDate());

	}

}

参考资料:

http://www.cnblogs.com/ycxyyzw/archive/2012/10/13/2722567.html

猜你喜欢

转载自blog.csdn.net/adobeid/article/details/43454157