注意:实现这此功能前,你需要会mybatis环境搭建!!
1. 创建User类
/** * @author boat */ public class User implements Serializable{ private Integer id; private String username; private Date birthday; private String sex; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } } 2. 创建dao接口
/** * @author boat */ public interface IUserDao { /** * 保存 * @param user * @return */ Integer addUser(User user); }
3. 创建IUserDao.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.boat.dao.IUserDao"> <!-- order="AFTER" 添加之后操作 keyProperty="id" 对象id keyColumn="id" 数据记录id resultType="Integer" 返回的类型 select last_insert_id(); 查询自增id,这属于mysql函数 --> <insert id="addUser" parameterType="com.boat.pojo.User"> <selectKey order="AFTER" keyProperty="id" keyColumn="id" resultType="Integer"> select last_insert_id(); </selectKey> insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}); </insert> </mapper>
4. 编写测试类
/** * @author boat */ public class MybatisTest { @Test public void testInsert() throws IOException { //1.读取配置文件 InputStream in = Resources.getResourceAsStream("mybatis.xml"); //2.创建SqlSessionFactory工厂 SqlSessionFactoryBuilder factory = new SqlSessionFactoryBuilder(); //3.使用工厂生产SqlSession对象 SqlSessionFactory build = factory.build(in); //4.使用SqlSession创建Dao接口的代理对象 SqlSession sqlSession = build.openSession(); IUserDao mapper = sqlSession.getMapper(IUserDao.class); User user = new User(); user.setUsername("boat"); user.setBirthday(new Date()); user.setSex("男"); user.setAddress("北京"); Integer integer = mapper.addUser(user); sqlSession.commit(); if(integer > 0){ System.out.println("保存成功"); } System.out.println(user); //关闭资源 sqlSession.close(); in.close(); } }