也许这个时间让我自己都有些害怕。
知道有很多项目用的不是hibernate,而是ibatis.早就想看看ibatis是什么货色了。但出于长久以来用的都是hibernate,多少对ibaits有点不屑的情绪。不过今天也算看了看,并且按照它的tutorial写了第一个小例子。对ibaits的优点平这样是找不到什么感觉的。不过有一点,它依赖的包很少,这个例子只需要一个ibatis-x.x.x.xxx.jar就可以了,当然还要有用到的jdbc驱动程序。
//成文1小时后添加的内容start////////////////////////////////////////////////
刚才也看了ibatis的guide。加上目录仅仅60多页而已。也就是好说,你可以在三个小时左右,掌握ibatis。可见ibaits的学习门槛很低。当然对于jee的老手才如此。如果平时用hibernate多,学起来会觉得更容易和简单。
//成文1小时后添加的内容end/////////////////////////////////////////////////
在官网上下的tutorial是一个很早的翻译成中文版本的,应该感谢译者的辛苦工作,虽然这个指导的例子连贯性并不是很好,而且缺乏“完整性”,给人一种不安全感。我想对于不怎么熟悉o/r映射的人员应该很容易出问题的。
我在这里不妨把经过我整改和调试通过的整个代码都贴出来,目录结构也是经我改过的。运行代码是个基于junit3.8的junit测试。
先把建立数据库的ddl贴出,在运行测试之前,先建立数据库和表
drop database if exists ibatis; create database ibatis DEFAULT CHARACTER SET utf8; use ibatis; drop table if exists person; CREATE TABLE PERSON( PER_ID int NOT NULL, PER_FIRST_NAME VARCHAR (40) NOT NULL, PER_LAST_NAME VARCHAR (40) NOT NULL, PER_BIRTH_DATE DATETIME , PER_WEIGHT_KG decimal(4, 2) NOT NULL, PER_HEIGHT_M decimal(4, 2) NOT NULL, PRIMARY KEY (PER_ID) );
tutorial/domain/Person.java
package tutorial.domain; import java.util.Date; public class Person { private int id; private String firstName; private String lastName; private Date birthDate; private double weightInKilograms; private double heightInMeters; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public double getWeightInKilograms() { return weightInKilograms; } public void setWeightInKilograms(double weightInKilograms) { this.weightInKilograms = weightInKilograms; } public double getHeightInMeters() { return heightInMeters; } public void setHeightInMeters(double heightInMeters) { this.heightInMeters = heightInMeters; } }
tutorial/maps/Person.xml
<?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 namespace="Person"> <select id="getPerson" resultClass="tutorial.domain.Person"> SELECT PER_ID as id, PER_FIRST_NAME as firstName, PER_LAST_NAME as lastName, PER_BIRTH_DATE as birthDate, PER_WEIGHT_KG as weightInKilograms, PER_HEIGHT_M as heightInMeters FROM PERSON WHERE PER_ID = #value# </select> <insert id="insertPerson" parameterClass="tutorial.domain.Person"> INSERT INTO PERSON (PER_ID, PER_FIRST_NAME, PER_LAST_NAME, PER_BIRTH_DATE, PER_WEIGHT_KG, PER_HEIGHT_M) VALUES (#id#, #firstName#, #lastName#, #birthDate#, #weightInKilograms#, #heightInMeters#) </insert> <update id="updatePerson" parameterClass="tutorial.domain.Person"> UPDATE PERSON SET PER_FIRST_NAME = #firstName#, PER_LAST_NAME = #lastName#, PER_BIRTH_DATE = #birthDate#, PER_WEIGHT_KG = #weightInKilograms#, PER_HEIGHT_M = #heightInMeters# WHERE PER_ID = #id# </update> <delete id="deletePerson" parameterClass="tutorial.domain.Person"> DELETE FROM PERSON WHERE PER_ID = #id# </delete> </sqlMap>
tutorial/MyAppSqlConfig.java
package tutorial; import java.io.Reader; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; public class MyAppSqlConfig { private static final SqlMapClient sqlMap; static { try { String resource = "tutorial/SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(resource); sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Error initializing MyAppSqlConfig class. Cause: " + e); } } public static SqlMapClient getSqlMapInstance() { return sqlMap; } }
tutorial/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"> <!-- Always ensure to use the correct XML header as above! --> <sqlMapConfig> <properties resource="tutorial/SqlMapConfig.properties" /> <settings cacheModelsEnabled="true" enhancementEnabled="true" lazyLoadingEnabled="true" maxRequests="32" maxSessions="10" maxTransactions="5" useStatementNamespaces="false" /> <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="tutorial/maps/Person.xml" /> </sqlMapConfig>
tutorial/SqlMapConfig.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ibatis?useUnicode=true&characterEncoding=utf8 username=your-dbuser-name password=your-dbuser-password
tutorial/test/ersonTest.java
package tutorial.test; import java.util.Date; import junit.framework.Assert; import junit.framework.TestCase; import tutorial.MyAppSqlConfig; import tutorial.domain.Person; import com.ibatis.sqlmap.client.SqlMapClient; public class PersonTest extends TestCase { public void testInsert() throws Exception { SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance(); Person newPerson = new Person(); newPerson.setId(1); newPerson.setFirstName("Clinton"); newPerson.setLastName("Begin"); newPerson.setBirthDate (new Date()); newPerson.setHeightInMeters(1.83); newPerson.setWeightInKilograms(86.36); sqlMap.insert("insertPerson", newPerson); } public void testGetPerson() throws Exception { SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance(); Person newPerson = (Person) sqlMap.queryForObject("getPerson", new Integer("1")); Assert.assertNotNull(newPerson); } public void testUpdate() throws Exception { SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance(); Person person = (Person) sqlMap.queryForObject("getPerson", new Integer("1")); person.setFirstName("三"); person.setLastName("张"); sqlMap.update("updatePerson", person); } public void testDelete() throws Exception { SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance(); Person person = (Person) sqlMap.queryForObject("getPerson", new Integer("2")); sqlMap.delete("deletePerson", person); } }
ok,小功告成。这就算是ibaits的hello world了。也许要发觉它的优点,只有在以后真正的应用到的时候。不过我奇怪的是这样的工具很简单,很容易学,我以前也写过类似的工具,某些企业的技术hr如果拿着这种经验当考核求职者的要件,那真是让人觉得可笑了。