ibatis的配置

来源:互联网 发布:linux tomcat加大内存 编辑:程序博客网 时间:2024/05/22 02:04

      iBATIS 是一个可以设计和实现更好的 Java/.NET 应用程序持久化层的框架。iBATIS 把对象和存储过程或者使用 XML 描述符的 SQL 语句进行了关联。下面我们将以

Student实体类为例,讲述他的配置文件的书写和SqlMapClient实例在类StudentDaoImpl中获取。

      1: SqlMap.properties 这个文件里面配置的就你要连接的数据库的驱动,用户名和密码。

driver=org.gjt.mm.mysql.Driver
url =jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8
username=xxx
password=######

    :2:  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>
<properties resource="com/broada/ibatis/SqlMap.properties"/>//加载SqlMap.properties配置文件
<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"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/xxx/ibatis/Student.xml"/>//加载Student.xml配置文件
</sqlMapConfig>

  :3: Student.xml具体的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMap>
<typeAlias alias="Student" type="com.xxx.ibatis.Student"/>//对com.xxx.ibatis.Student进行简化为Student
<insert id="insertStudent" parameterClass="Student">//id是一个事务处理的一个具体标识,parameterClass参数的类型
insert into student(id ,name , score , address )
values             (#id#, #name#, #score#, #address# )

</insert>
<select id="selectStudents" resultClass="Student">
select * from student
</select>
<select id="selectStudentsByName" resultClass="Student">//resultClass返回值的类型

select * from student where name= (#name#)
</select>
<delete id="deleteStudent" parameterClass="int">
delete from student where id= (#id#)
</delete>
<delete id="deleteStudentByName" parameterClass="String">
delete from student where name= (#name#)
</delete>
</sqlMap>

   4:在StudentDaoImpl中获取SqlMapClient的片段代码其中这是一个静态块

static {
  try {
   Reader reader=Resources.getResourceAsReader("com/broada/ibatis/SqlMapCogfig.xml");
   sqlMapClient=SqlMapClientBuilder.buildSqlMapClient(reader);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

注意:要导入二个必须的包(具体的数据库驱动包和,ibatis-2[1].3.0.677.jar)具体工程的结构