发表时间:2009-05-05
最后修改:2009-05-05
前段时间做毕业设计,新学习了ibatis,感觉很好用,比hibernate要灵活很多,而且配置也少了不少。
现在写一个ibatis的入门例子,分享一下。
1.SqlMapConfigExample.properties
这个文件放你要连接数据库的一些参数
username=sa password=1234 url=jdbc:sqlserver://192.168.0.22:1433;DatabaseName=testdb driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
|
2.SqlMapConfigExample.xml
这个是sqlMap的配置文件,
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!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="SqlMapConfigExample.properties" /> <settings cacheModelsEnabled="true" lazyLoadingEnabled="false" enhancementEnabled="true" maxSessions="64" maxTransactions="8" maxRequests="128" />
<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" /> <property value="15" name="Pool.MaximumActiveConnections" /> <property value="15" name="Pool.MaximumIdleConnections" /> <property value="1000" name="Pool.MaximumWait" /> </dataSource> </transactionManager>
<sqlMap resource="User.xml" />
</sqlMapConfig>
|
3.User.java
package example.sqlmap.bean;
public class User { private int id; private String username; private String password;
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; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
|
4.User.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"> <typeAlias alias="employee" type="example.sqlmap.bean.Employee"/> <select id="getUser" resultClass="example.sqlmap.bean.User" parameterClass="example.sqlmap.bean.User"> select id as id, name as username, password as password from users WHERE name = #username# and password = #password#; </select> </sqlMap>
|
ok,有这四个文件就搞定了,再写一个测试的类就行了,我把源代码发上来了,有兴趣的可以看看