ibatis学习一------入门,第一个例子
虽然现在ibatis项目已由apache转移到googlecode,改名为mybatis,进入3.*版本后更容易使用,但是现在大多数公司还未升级到mybatis(起码老大开会是这么说的)。现在从头开始学习ibatis。先做一下入门的例子,然后一边写demo一边学习。个人水平有限,写不出深入分析理论的文章,就按着代码+注释+说明的方式写下自己的学习历程。
eclipse下新建项目,在lib下加入要用到的包。ibatis的包现在要到googlecode下载,http://code.google.com/p/mybatis/ ,点击Downloads,页面下面的的All Downloads,可找到ibatis包。
在数据库中新建数据库si_test,新建表product,并插入两条数据。
create table product(
id int auto_increment,
name varchar(50),
number int,
primary key(id))
insert into product(name, number)
values('computer', 100),
('phone', 800)
在项目中新建POJO类Product,实现Serializable接口,重写toString方法。
1 import java.io.Serializable; 2 3 /** 4 * @author apl 5 *2012-12-26 下午3:01:51 6 *TODO Product的pojo类 7 */ 8 public class Product implements Serializable{ 9 private Integer Pid; 10 private String name; 11 private Integer number; 12 13 /** 14 * 重写toString方法 15 */ 16 public String toString(){ 17 return "Product [Pid=" + Pid + ", name=" + name + ", number=" + number + "]"; 18 } 19 20 //省略构造方法和get、set方法 21 }
新建product的sqlMap映射文件product.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE sqlMap 3 PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" 4 "http://ibatis.apache.org/dtd/sql-map-2.dtd"> 5 6 <sqlMap> 7 <!-- 别名,方便引用 --> 8 <typeAlias alias="Product" type="ibatis.model.Product"/> 9 10 <!-- 获取所有信息 --> 11 <select id="getProductInfo" resultClass="Product"> 12 select id as Pid, name, number from product 13 </select> 14 </sqlMap>
新建数据库的配置文件jdbc.properties,指定utf8编码,日期全为0则返回空值null
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/si_test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=root
新建ibatis配置文件SqlMapConfig.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE sqlMapConfig 3 PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" 4 "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> 5 <sqlMapConfig> 6 <properties resource="jdbc.properties" /> 7 <transactionManager type="JDBC"> 8 <dataSource type="SIMPLE"> 9 <property name="JDBC.Driver" value="${jdbc.driverClassName}" /> 10 <property name="JDBC.ConnectionURL" value="${jdbc.url}" /> 11 <property name="JDBC.Username" value="${jdbc.username}" /> 12 <property name="JDBC.Password" value="${jdbc.password}" /> 13 </dataSource> 14 </transactionManager> 15 <sqlMap resource="ibatis/resources/User.xml" /> 16 <sqlMap resource="ibatis/resources/product.xml"/> 17 </sqlMapConfig>
最后写一个测试demo,运行一下。
1 public class ProductDemo { 2 public static void main(String[] args) throws IOException, SQLException{ 3 String config = "ibatis/SqlMapConfig.xml"; 4 Reader reader = Resources.getResourceAsReader(config); 5 SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); 6 List<Product> list = sqlMap.queryForList("getProductInfo"); 7 for(Product product : list){ 8 System.out.println(product); 9 } 10 } 11 }