实现目的:
ibatis基本环紧架设,完成对Person表的基本操作.
数据库:SqlServer
表:Person
Person.sql
use
[
IbatisTest
]
GO
if
exists
(
select
*
from
dbo.sysobjects
where
id
=
object_id
(N
'
[dbo].[Person]
'
)
and
OBJECTPROPERTY
(id, N
'
IsUserTable
'
)
=
1
)
drop
table
[
dbo
]
.
[
Person
]
GO
CREATE
TABLE
[
dbo
]
.
[
Person
]
(
[
PersonId
]
[
int
]
IDENTITY
(
1
,
1
)
NOT
NULL
,
[
PersonName
]
[
nvarchar
]
(
50
) COLLATE Chinese_PRC_CI_AS
NOT
NULL
,
[
PersonAge
]
[
int
]
NULL
,
[
PersonEmail
]
[
nvarchar
]
(
50
) COLLATE Chinese_PRC_CI_AS
NULL
)
ON
[
PRIMARY
]
GO
根据数据库的到domain如下:
Person.java
package yidishui.domain;
public class Person {
private int personId;
private String personName;
private int personAge;
private String personEmail;
/**//*geter and seter*/
}
要实现结果定义Dao接口如下:
PersonDao.java
package yidishui.dao;
import yidishui.domain.Person;
import java.util.List;
import java.sql.SQLException;
public interface PersonDao {
public void insertPerson(Person person) throws SQLException;
public void updatePerson(Person person) throws SQLException;
public Person getPersonById(int personId) throws SQLException;
public void deletePerson(int personId) throws SQLException;
public List allPersonList() throws SQLException;
}
现在要通过Ibatis实现完成以上接口内容,测试(这里只有正确行测试):
PersonDaoImplTest.java
package yidishui.daoIbatisImpl;
import junit.framework.*;
import yidishui.daoIbatisImpl.PersonDaoImpl;
import yidishui.domain.Person;
import yidishui.dao.PersonDao;
import java.sql.SQLException;
import java.util.List;
public class PersonDaoImplTest extends TestCase {
public void testInsertPerson() {
PersonDao personDao = new PersonDaoImpl();
Person person = new Person();
person.setPersonName("yidishui");
person.setPersonEmail("yidishui1570@gamil.com");
person.setPersonAge(100);
try {
personDao.insertPerson(person);
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void testUpdatePerson() throws Exception {
PersonDao personDao = new PersonDaoImpl();
Person person = new Person();
person.setPersonId(1);
person.setPersonName("yidishui_update");
person.setPersonEmail("yidishui1570@gamil.com");
person.setPersonAge(24);
personDao.updatePerson(person);
}
public void testDeletePerson() throws Exception {
PersonDao personDao = new PersonDaoImpl();
personDao.deletePerson(1);
}
public void testAllPersonList() throws Exception {
PersonDao personDao = new PersonDaoImpl();
List list = personDao.allPersonList();
assertTrue("list size is 0", list.size() > 0);
for (int i = 0; i < list.size(); i++) {
Person person = (Person) list.get(i);
System.out.println(person.getPersonName());
}
}
}
完成测试任务完成:)
具体Ibatis配置:
一.jar说明
ibatis-common-*.jar ibatis公用工具类
ibatis-dao-*.jar ibatis Sql Maps框架
ibatis-sqlmap-*.jar ibatis Dao 框架
junit.jar
log4j.jar
二.database.properties存放数据库链接信息
driver=net.sourceforge.jtds.jdbc.Driver
url=jdbc:jtds:sqlserver://localhost:1433/DataBaseName;tds=8.0;lastupdatecount=true
username=sa
password=***
注:这里使用SqlServer数据库,驱动使用jtds下载网址http://jtds.sourceforge.net/
三.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">
<sqlMapConfig>
<properties resource="database.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}"/>
<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 ACCOUNT"/>
<property name="Pool.PingEnabled" value="false"/>
<property name="Pool.PingConnectionsOlderThan"
value="1"/>
<property name="Pool.PingConnectionsNotUsedFor"
value="1"/>
</dataSource>
</transactionManager>
<sqlMap resource="yidishui/daoIbatisImpl/sql/Person.xml"/>
</sqlMapConfig>
三.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>
<typeAlias alias="Person" type="yidishui.domain.Person"/>
<resultMap id="personMap" class="Person">
<result property="personName" column="PersonName"></result>
<result property="personId" column="personId"></result>
<result property="personAge" column="personAge"></result>
<result property="personEmail" column="personEmail"></result>
</resultMap>
<insert id="insertPerson" parameterClass="Person">
INSERT INTO Person
( PersonName, PersonAge, PersonEmail)
Values
(#personName#,#personAge#,#personEmail#)
</insert>
<update id="updatePerson" parameterClass="Person">
UPDATE Person SET
PersonName=#personName#,PersonAge=#personAge#,PersonEmail=#personEmail#
WHERE PersonId=#personId#
</update>
<delete id="deletePerson" parameterClass="int">
DELETE Person WHERE PersonId=#personId#
</delete>
<select id="getPersonById" parameterClass="int" resultClass="Person">
SELECT
PersonId,PersonName,PersonAge,PersonEmail
FROM Person
WHERE PersonId=#personId#
</select>
<select id="allPersonList" resultMap="personMap">
SELECT
PersonId,PersonName,PersonAge,PersonEmail
FROM Person
</select>
</sqlMap>
四:SqlMapClient
package yidishui.daoIbatisImpl;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.common.resources.Resources;
import java.io.Reader;
public class IbatisSqlMapClient {
private static final SqlMapClient sqlMap;
static {
try {
String resource = "yidishui/daoIbatisImpl/sql/SqlMapConfig.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error initializing IbatisSqlMap class.Cause;" + e);
}
}
public static SqlMapClient instance() {
return sqlMap;
}
} 五:Dao实现
package yidishui.daoIbatisImpl;
import yidishui.dao.PersonDao;
import yidishui.domain.Person;
import java.util.List;
import java.sql.SQLException;
public class PersonDaoImpl implements PersonDao {
public void insertPerson(Person person) throws SQLException {
IbatisSqlMapClient.instance().insert("insertPerson", person);
}
public void updatePerson(Person person) throws SQLException {
IbatisSqlMapClient.instance().update("updatePerson", person);
}
public Person getPersonById(int personId) throws SQLException {
return (Person) IbatisSqlMapClient.instance().queryForObject("getPersonById", personId);
}
public void deletePerson(int personId) throws SQLException {
IbatisSqlMapClient.instance().delete("deletePerson", personId);
}
public List allPersonList() throws SQLException {
return IbatisSqlMapClient.instance().queryForList("allPersonList", null);
}
}
六.添加打印日志Log4j支持(log4j.properties)
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# SqlMap logging configuration
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
# Console output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
#sqlmap
#dao
七,运行测试Ok:)
配置完成