准备MyBatis环境
相关的?jar包:?Oracle,?ibatis?都要。
?
需要3个重要文件:JDBC连接配置文件、ibatis核心文件、实体类映射文件
?
JDBC?至少需要配置四个属性:?username,password,驱动类名,url。
-------------------------------------------
SqlMap.properties配置:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=ht
password=ht
-------------------------------------------
?
ibatis核心文件:
<?xml version="1.0" encoding="UTF-8" ?>
?<!--
??iBatis 和 MyBatis 的全局配置文件使用不同的 DTD 约束,在将应用由 iBatis 升级至 MyBatis
??时需要注意(两者的映射文件 DTD 约束也不相同)
?-->
?<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
?<!-- jdbc连接DB配置文件 -->
?<properties resource="com/ibatis/SqlMap.properties"></properties>
?
?<!-- 起别名 -->
?<typeAliases>
??<typeAlias alias="Student" type="com.ibatis.model.Student" />
?</typeAliases>
?
?<!-- 配置数据源相关的信息 -->
?<environments default="demo">
??<environment id="demo">
???<transactionManager type="JDBC" />
???<dataSource type="POOLED">
????<property name="driver" value="${driver}" />
????<property name="url" value="${url}" />
????<property name="username" value="${username}" />
????<property name="password" value="${password}" />
???</dataSource>
??</environment>
?</environments>
?<!-- 列出映射文件 -->
?<mappers>
??<mapper resource="com/ibatis/model/Student.xml" />
?</mappers>
</configuration>
?
------------------------------------------------------
?
创建实体类Student:
package com.ibatis.model;
?
public class Student {
?private int s_id;
?private String s_name;
?private int s_age;
?
?public int getS_id() {
??return s_id;
?}
?public void setS_id(int sId) {
??s_id = sId;
?}
?public String getS_name() {
??return s_name;
?}
?public void setS_name(String sName) {
??s_name = sName;
?}
?public int getS_age() {
??return s_age;
?}
?public void setS_age(int sAge) {
??s_age = sAge;
?}
?
?@Override
?public String toString() {
??return "Student: id=" + s_id + " name=" + s_name + " age=" + s_age;
?}
?
}
--------------------------------------------------
?
创建映射文件Student.xml:
<?xml version="1.0" encoding="UTF-8" ?>
?<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 这里namespace必须是IStudentDAO接口的路径,不然要运行的时候要报错 “is not known to the MapperRegistry”-->
<mapper namespace="com.ibatis.dao.IStudentDAO">
?
</mapper>