日期:2014-05-16  浏览次数:20548 次

ibatis使用小结
1.搭建环境
  导入相关的jar包,如 classes12.jar和ibatis-2.3.4.726.jar

2.配置文件

  ①jdbc连接的属性文件(SqlMap.properties)
  
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=scott
password=tiger



  ②总配置文件(SqlMapConfig.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
	<properties resource="org/test/sql/SqlMap.properties" />
	<settings useStatementNamespaces="true" />
	<!-- 事务管理,采用JDBC -->
	<transactionManager type="JDBC">
		<!-- 数据源,简单数据源,读取properties文件 -->
		<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="org/test/dao/User.xml"/>

</sqlMapConfig>




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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap>
 <typeAlias alias="User" type="org.test.vo.User"/>
 
 <select id="findLogin" resultClass="User" parameterClass="String">
 select name from userlogin where userid=#userid# and password=#password#
 </select>



</sqlMap>

parameterClass的值不区分大小写

vo最好写一个无参的构造方法,否则反射机制可能会出问题

3.读取配置

public class UserDAOImpl implements IUserDAO {

	//读取配置
	private static SqlMapClient SqlMapClient = null;
	static{
		
		try {
			Reader reader = com.ibatis.common.resources.Resources.getResourceAsReader("org/test/sql/SqlMapConfig.xml");
			SqlMapClient = com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}