项目目录:
mybatis.cfg.xml 配置文件用来配置数据源和 Mappper
mybatis.cfg.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--
可以引用多个外置配置文件
--!>
<properties resource="mysql.properties"></properties>
<!-- 配置mybatis运行环境 -->
<environments default="xxx">
<environment id="xxx">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="JDBC" />
<!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
<!-- POOLED 表示支持JDBC数据源连接池 -->
<!-- UNPOOLED 表示不支持数据源连接池 -->
<!-- JNDI 表示支持外部数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射对应类接口--!>
<mapper resource="com/kx/mapper/StudentBeanMapper.xml"/>
<!--
搜索这个包下的所有配置文件
<mapper packpage="com/kx/mapper"/>
--!>
</mappers>
</configuration>
接口配置文件.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--必须写清楚,不然会出现 type interface is not know--!>
<mapper namespace="com.kx.mapper.StudentBeanMapper">
<!--结果集--!>
<resultMap id="StudentBeanMapper" type="com.kx.domain.StudentBean">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="age" column="age" />
</resultMap>
<insert id="insert" >
insert into t_stu (id,username,age) values (#{id},#{username},#{age})
</insert>
<update id="update">
update t_stu set username=#{username} where id=#{id}
</update>
<!--resultMap 查询返回结果集 --!>
<select id="selectById" resultMap="StudentBeanMapper" >
select * from t_stu where id=#{id}
</select>
</mapper>
接口
public interface StudentBeanMapper {
void insert(StudentBean stu);
void update(StudentBean stu);
StudentBean selectById(int id);
}
工具类
public class myBatisTool {
public static SqlSessionFactory sf;
static{
try {
InputStream in = Resources.getResourceAsStream("mybatis.cfg.xml");
sf=new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
}
}
public static SqlSession getSession(){
return sf.openSession();
}
}
测试代码
@Test
public void test(){
select();
}
public static void select(){
SqlSession session=myBatisTool.getSession();
StudentBeanMapper stuMap= session.getMapper(StudentBeanMapper.class);
StudentBean stu=stuMap.selectById(1);
System.out.println(stu.toString());
session.commit();
session.close();
}