1 创建表
create_table.sql 文件内容:
create table address(
id int primary key,
employee_id int not null,
street varchar(200),
home_no int,
address1 varchar(200),
address2 varchar(300)
)
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings useStatementNamespaces="true"/>
<typeAlias alias="Employee" type="com.softtek.Employee"/>
<typeAlias alias="Person" type="com.softtek.Person2"/>
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/test"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value="jinbingchuan"/>
</dataSource>
</transactionManager>
<sqlMap resource="Employee.xml"/>
<sqlMap resource="Person.xml"/>
</sqlMapConfig>
这里主要是配置数据源和事务管理使用jdbc.
测试代码为
package com.softtek;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.ibatis.common.jdbc.ScriptRunner;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
/*
@Author
@Create Date 2013-2-7 下午2:39:31
@Place ShangHai
@Version 1.0
*/
public class RunScriptTest {
private SqlMapClient smc;
@Before
public void init() throws IOException{
smc = SqlMapClientBuilder.buildSqlMapClient(Resources.getResourceAsReader("SqlMapConfig.xml"));
}
@Test
public void testRunScript(){
Connection conn = null;
try {
conn = smc.getDataSource().getConnection();
ScriptRunner scriptRunner = new ScriptRunner(conn,false,true);
Reader reader = Resources.getResourceAsReader("create_table.sql");
scriptRunner.runScript(reader);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}