MyBatis-05 插入数据


添加映射

<?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.cd.StudentMapper">

  <insert id="insertStudent" parameterType="com.cd.Student"  useGeneratedKeys="true">
    insert into stu_tbl(name,age) values(#{name},#{age})
  </insert>

</mapper>

添加

package com.cd;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test {
    public static void main(String[] args) {
        String resource = "com/cd/mybatis-config.xml";
        InputStream inputStream;
        try {
            inputStream = (InputStream) Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();

            Student stu = new Student();

            stu.setName("tom");
            stu.setAge(20);

            session.insert("com.cd.StudentMapper.insertStudent", stu);
            session.commit();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


原文链接:http://codingdict.com/