1.获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
配置文件mybatis-config.xml的各项配置,后续章节会单独讲解。
2.获取SqlSession对象
SqlSession session = sqlSessionFactory().openSession(true);
SqlSession openSession(boolean autoCommit):true表示自动提交
SqlSession代表和数据库的一次会话,用完必须关闭。
同样,sqlsession和connecttion一样,都是线程不安全的,每次使用,都要去获取。
3.获取接口的代理对象MapperProxy
1.首先自定义个Mapper接口
public interface StudentMapper {
public int addStudent(Student s);
public int updateStudent(Student s);
public int deleteById(Long id);
public Student findOneById(Long id);
public Student findAll();
}
2.定义mapper接口对用的sql.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="com.licw.lean.mybatis_anayl.StudentMapper">
<insert id="addStudent" parameterType="com.licw.lean.mybatis_anayl.Student">
INSERT INTO studentTab
(name,age) VALUES (#{name},#{age})
</insert>
<update id="updateStudent" parameterType="com.licw.lean.mybatis_anayl.Student">
UPDATE studentTab SET
name =#{name},age=#{age} WHERE id=#{id}
</update>
<delete id="deleteById" parameterType="java.lang.Long">
DELETE FROM studentTab
WHERE id =#{id}
</delete>
<select id="findOneById" parameterType="java.lang.Long">
SELECT * FROM studentTab
WHERE id=#{id}
</select>
<select id="findAll" resultType="com.licw.lean.mybatis_anayl.Student">
SELECT * FROM studentTab
</select>
</mapper>
3.通过SqlSeesion获取Mapper的代理
StudentMapper mapper = session.getMapper(StudentMapper.class);
4.执行增删改查方法
Student s = new Student("12344", 32);
int nums = mapper.addStudent(s);
5.关闭session
session.close();
以上5个步骤中,抛出异常部分没有写出来,实际写代码过程中,要注意异常的捕获,因为这个不是本系列的重点,就不罗列了