使用MyBatis工具类增删查改
在前面的基础上,使用上篇的工具类,做基本的增删查改操作。
数据库原始情况
mapper.StudentMapper(映射器接口)
package mapper;
import model.Student;
//Student类的映射器接口,参数/返回值/函数名都要和XML文件中匹配
public interface StudentMapper {
//查
Student getStudent(int id);
//增
void addStudent(Student student);
//删
void deleteStudent(int id);
//改
void updateStudent(Student student);
}
mapper/StudentMapper.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">
<!--命名空间用映射器接口的全名-->
<mapper namespace="mapper.StudentMapper">
<!--用select元素定义一个查询SQL,id用接口中的方法名-->
<!--parameterType指定传入的参数类型,resultType指定返回的参数类型,参数类型可用别名(配置文件中定义的)-->
<select id="getStudent" parameterType="int" resultType="stu">
SELECT
id,
name AS stuName
FROM student
WHERE id = #{id}
</select>
<!--用insert元素定义一个插入SQL,给出方法名和传入参数类型-->
<insert id="addStudent" parameterType="stu">
INSERT INTO student (name) VALUES (#{stuName})
</insert>
<!--用delete元素定义一个删除SQL,给出方法名和传入参数类型-->
<delete id="deleteStudent" parameterType="int">
DELETE FROM student
WHERE id = #{id}
</delete>
<!--用update元素定义一个更新SQL,给出方法名和传入参数类型-->
<update id="updateStudent" parameterType="stu">
UPDATE student
SET name = #{stuName}
WHERE id = #{id}
</update>
</mapper>
Main(程序入口)
import mapper.StudentMapper;
import model.Student;
import org.apache.ibatis.session.SqlSession;
import util.SqlSessionFactoryUtil;
public class Main {
public static void main(String[] args) {
SqlSession sqlSession = null;
try {
//调用工具类的静态方法开启并获取一个SqlSession实例
sqlSession = SqlSessionFactoryUtil.openSqlSession();
//获取映射器代理类对象
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
//插入学生类对象
Student student = new Student();
student.setStuName("新的学生");
studentMapper.addStudent(student);
//查询学生类对象
student = studentMapper.getStudent(3);
System.out.println("查询到了:" + student.getId() + "," + student.getStuName());
//修改学生类对象
student.setStuName("学生3的新名字");
studentMapper.updateStudent(student);
//删除一个学生
studentMapper.deleteStudent(2);
//提交事务
sqlSession.commit();
} catch (Exception e) {
//发生异常时打印异常信息
System.err.println(e.getMessage());
//回退
if (null != sqlSession)
sqlSession.rollback();
} finally {
//在finally块中关闭SqlSession对象
if (null != sqlSession)
sqlSession.close();
}
}
}
运行结果
从之前配置使用输出的log4j日志中可以看到执行了哪些SQL语句,传入的参数和查询到(或发生影响)的行数,以及最终事务正常提交了:
数据库内:
注
对于增删改这样能影响数据库表的操作,可以让Mapper接口中的方法返回int而不是这里的void,则使用时可以获取发生影响的行数。