2006年05月03日

     最近的项目在用ibatis进行数据库操作,由于这方面的资料相对不多,为了让初学者容易上手,我写了一个比较简单的ibatis配置,没有用接口,工厂和DAO进行操作,目的就是希望让大家更容易理解。IDE 用idea5.0,数据库是用SQLserver2000,SQL脚本如下:

if exists (select * from dbo.sysobjects where id = object_id(N’[dbo].[userInfo]‘) and OBJECTPROPERTY(id, N’IsUserTable’) = 1)
drop table [dbo].[userInfo]
GO

CREATE TABLE [dbo].[userInfo] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[userName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO

文件的目录结构如下(在idea5.0中):



每个文件的源代码如下:
UserInfo.java


package module;

public class UserInfo {
private int id;
private String userName;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}
}

UserInfo.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">
<!–这里只写了一个select,其他写法请参考有关书籍–>
<sqlMap namespace="userInfo">
<!–定义映射文件的别名,比如此XML文件中就用u代替了module.UserInfo,这样就不用在每个地方写出class的全名–>
<typeAlias alias="u" type="module.UserInfo"/>

<select id="getUser" resultClass="u" parameterClass="u">
select * from userInfo where id=#id#
</select>

</sqlMap>

SqlMapClientInit.java

package init;

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

import java.io.Reader;
//初始化SqlMapClient;

public class SqlMapClientInit {
private static SqlMapClient sqlMapClient = null;

static {
try {
String resource = "conf/sqlmapconfig.xml";

Reader reader = null;
reader = Resources.getResourceAsReader(resource);

if (sqlMapClient == null) {
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
}

 

db.properties

#用来设置数据库的连接参数;根据用户的具体环境设置;
driverClassName=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Test;SelectMethod=cursor
username=sa
password=1111

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">
<!–这是ibatis的主要配置文件–>
<sqlMapConfig>
<!–引用数据库的配置文件–>
<properties resource="conf/db.properties" />
<!–有关这个配置文件每个参数的意义,请参考具体ibatis的资料,一般按照他的默认设置就行了–>
<!–useStatementNamespaces=“true”:用来设置是否使用statement的命名空间
比如在Test的main方法中调用UserInfo.xml的getUser使用了命名空间加方法名的方式
newUser=(UserInfo)sqlMapClient.queryForObject("userInfo.getUser",user);
如果useStatementNamespaces=“false”则直接写成getUser 调用就行了;
–>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="true"
/>

<transactionManager type="JDBC" >
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="${driverClassName}"/>
<property name="JDBC.ConnectionURL" value="${url}"/>
<property name="JDBC.Username" value="${username}"/>
<property name="JDBC.Password" value="${password}"/>
<property name="JDBC.DefaultAutoCommit" value="true" />
<property name="Pool.MaximumActiveConnections" value="10"/>
<property name="Pool.MaximumIdleConnections" value="5"/>
<property name="Pool.MaximumCheckoutTime" value="120000"/>
<property name="Pool.TimeToWait" value="500"/>
<property name="Pool.PingQuery" value="select 1 from author"/>
<property name="Pool.PingEnabled" value="false"/>
<property name="Pool.PingConnectionsOlderThan" value="1"/>
<property name="Pool.PingConnectionsNotUsedFor" value="1"/>
</dataSource>
</transactionManager>
<!–指定映射文件的位置–>
<sqlMap resource="module/maps/UserInfo.xml" />
</sqlMapConfig>

Test.java

import module.UserInfo;
import init.SqlMapClientInit;
import com.ibatis.sqlmap.client.SqlMapClient;

public class Test {
public static void main(String args[]) throws Exception {


UserInfo user=new UserInfo();
UserInfo newUser=null;

user.setId(1);
SqlMapClient sqlMapClient=null;
sqlMapClient=SqlMapClientInit.getSqlMapClient();
if(sqlMapClient!=null){
newUser=(UserInfo)sqlMapClient.queryForObject("userInfo.getUser",user);
}

if(newUser!=null){
System.out.println("newUser.getUserName() = " + newUser.getUserName());
}

}
}

这样一个基本的ibatis的环境就建立了。运行Test.java,可以从数据库中查到id号等于1的一条记录;其他ibatis的具体操作请参考相关书籍;