(一 )操作
1.自己构建工具类SqlSessionFactory
2.在测试类中的代码
SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student s = new Student("王五",18);
int n = studentMapper.add(s);
sqlSession.commit();
最后一定要commit
(二) 文件配置
1.配置 主配置文件 mybatis-config.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>
<!-- jdbc的属性文件 -->
<properties resource="jdbc.properties"/>
<typeAliases>
<!-- 一般这里要引入自己定义的类 -->
<typeAlias alias="Student" type="com.czp.model.Student"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 配置model类对应的mapper的路径 -->
<mapper resource="com/czp/mappers/StudentMapper.xml" />
</mappers>
</configuration>
2.构建模型类
3.构建模型类对应的mapper
4.配置StudentMapper.xml 放跟mapper同一个包下
<?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">
<mapper namespace="com.czp.mappers.StudentMapper">
<insert id="add" parameterType="Student" >
insert into t_student values(null,#{name},#{age})
</insert>
</mapper>