OOP编程iBatis 学习笔记之- 环境配置及简单例子测试
本人使用MYSQL数据库做为测试例子 ,因为本例子简单,故没有将生成表的代码贴上
环境配置
1. 导入ibatis-2.3.4.726.jar mysql-connector-java-5.1.6-bin.jar
导入配置文件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>
<properties resource="com/itcast/SqlMap.properties"/>
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property value="${driver}" name="JDBC.Driver"/>
<property value="${url}" name="JDBC.ConnectionURL"/>
<property value="${username}" name="JDBC.Username"/>
<property value="${password}" name="JDBC.Password"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/it/Note.xml"/>
</sqlMapConfig>
SqlMap.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1/test
username=root
password=admin
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>
<typeAlias alias="Note" type="com.it.Student"/>
<select id="selectAllNote” resultClass=" Note">
select *
from student
</select>
</sqlMap>
2. 建立对应表-类文件
3. package com.it;
4.
5. import java.sql.Date;
6. //Author:meetweb@sohu.com
7. public class Note {
8. private int sid=0;
9. private String sname=null;
10. private String major=null;
11. private Date birth=null;
12. }
执行文件
package com.it;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.sqlmap.client.SqlMapClient;
public class IStudentDAOImpl implements IStudentDao {
private static SqlMapClient sqlMapClinet=null;
static {
Reader reader;
try {
reader = com.ibatis.common.resources.Resources.getResourceAsReader("com/it/SqlMapConfig.xml");
sqlMapClinet=com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<Note> queryAllN() {
// TODO Auto-generated method stub
List<Note> studentList =null;
try {
studentList=sqlMapClinet.queryForList("selectAllNote");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return studentList;
}
public static void main(String[] args){
IStudentDao dao=new IStudentDAOImpl();
//dao.queryAllStudent();
System.out.println("OK");
//List<Student> myList=dao.queryAllStudent();
for(Note student :dao.queryAllStudent()){
System.out.println(student.getSname());
}
}
}