这篇是承接上一篇的helloWorld程序。首先将一系列初始化的步骤再做一个工厂类进行包装,代码如下:
package com.tinaluo.sun; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.*; public class FKSqlSessionFactory { private static SqlSessionFactory sqlSessionFactory=null; static{ try { InputStream inputStream=Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } catch(Exception e) { e.printStackTrace(); } } public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(); } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } }
UserMapper.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="org.fkit.mapper.UserMapper"> <!-- 增加 --> <insert id="saveUser" parameterType="com.tinaluo.sun.User" useGeneratedKeys="true"> insert into tb_user(name,sex,age) values(#{name},#{sex},#{age}) </insert> <!-- 查找 --> <select id="selectUser" parameterType="int" resultType="com.tinaluo.sun.User"> select * from tb_user where id=#{id} </select> <!-- 更新 --> <update id="modifyUser" parameterType="com.tinaluo.sun.User"> update tb_user set name=#{name},sex=#{sex},age=#{age} where id=#{id} </update> <!-- 删除 --> <delete id="removeUser" parameterType="int"> delete from tb_user where id=#{id} </delete> </mapper>