一、接口方法
/** * 删除、修改、添加操作都可以返回三种类型 * Integer、Long、Boolean */ public interface MyUserMapper { public MyUser selectMyUser(Integer id); public Integer updateMyUser(MyUser user); public Boolean addMyUser(MyUser user); public Long deleteMyUser(Integer id); }
二、对应的 SQL 映射文件
<?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"> <!-- namespace 对应接口文件的全路径 --> <mapper namespace="com.dao.MyUserMapper"> <!--resultType 返回参数类型,可用别名--> <select id="selectMyUser" resultType="myUser"> select * from myuser where id = #{id} </select> <!--parameterType 输入参数类型,可用别名--> <update id="updateMyUser" parameterType="myUser"> update myuser set name=#{name},age=#{age} where id=#{id} </update> <!--useGeneratedKeys 返回插入主键 , keyProperty 把主键封装到 Bean 的那个字段--> <insert id="addMyUser" parameterType="myUser" useGeneratedKeys="true" keyProperty="id"> insert into myuser(name,age) values (#{name},#{age}) </insert> <delete id="deleteMyUser" parameterType="integer"> delete from myuser where id=#{id} </delete> </mapper>
三、测试
单独使用 mybatis 框架进行增、删、改操作时,要显示的提交事务。session.commit(),不然会出现如下日志,且无法对数据库成功操作。
Rolling back JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@291ae] Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@291ae]
测试代码
public static void main(String[] args) { SqlSession session = null; try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); session = sqlSessionFactory.openSession(); MyUserMapper mapper = session.getMapper(MyUserMapper.class); MyUser myUser = new MyUser(null,"zhangsan",21); mapper.addMyUser(myUser); session.commit(); System.out.println("主键:"+myUser.getId()); } catch (IOException e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } } }
若为非自增主键(oracle)
<!-- 获取非自增主键的值:每次插入数据的主键是从另一张表中拿到的值 --> <insert id="addUser" databaseId="oracle"> <!-- keyProperty 把查出主键封装到 Bean 的那个字段 order BEFORE:先运行 selectKey 查询 id 的 SQL,查出 id 值封装给 javaBean 的 id 属性 AFTER:先运行插入的 SQL,再运行 selectKey 查询 id 的 SQL resultType 查出的数据的返回值类型 --> <selectKey keyProperty="id" order="BEFORE" resultType="Integer"> <!-- 查询主键的sql语句 --> select EMPLOYEES_SEQ.nextval from dual </selectKey> insert into myuser(name,age) values (#{name},#{age}) </insert>
http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#insert_update_and_delete