mybatis主键自增

2018-05-30  本文已影响0人  百年叔叔

我们在用mybatis进行插入的时候需要返回一个自增的主键。
这个文章分为以下几步
1.建表

/*
 Navicat Premium Data Transfer

 Source Server         : 本地
 Source Server Type    : MySQL
 Source Server Version : 50720
 Source Host           : localhost:3306
 Source Schema         : mybatis

 Target Server Type    : MySQL
 Target Server Version : 50720
 File Encoding         : 65001

 Date: 29/05/2018 08:23:06
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tbl_employee
-- ----------------------------
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

这个表有4个字段
分别是 id
last_name
gender
email

对应的实体类

    private Integer id; 
    private String lastName;
    private String email;
    private String gender;

/**dao层**/
/**
     * 添加一个员工信息
     * @param employee 员工信息的实体类
     */
    Long addEmp(Employee employee);

/**xml*/
 <!--新增一条记录-->
    <insert id="addEmp" parameterType="employee" >
        INSERT INTO tbl_employee(last_name,email, gender) VALUES (#{lastName},#{email},#{gender})
    </insert>

2.正常插入数据不返回主键id
现在我们写一个测试方法

 @Test
    public void test04() throws IOException {
        // 1、获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        // 2、获取sqlSession对象并设置自动提交
        SqlSession openSession = sqlSessionFactory.openSession(true);
        try {
            // 3、获取接口的实现类对象
            //会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);


            Employee emp=new Employee(null,"tom","168@qq.com","1");
             mapper.addEmp(emp);
             //获取主键id
            System.out.println("主键id的值:"+emp.getId());
        } finally {
            openSession.close();
        }
    }

3.返回主键id

如果需要返回主键id 我们只需要在xml 里面加上

 <!--新增一条记录-->
    <insert id="addEmp" parameterType="employee" useGeneratedKeys="true" keyProperty="id" >
        INSERT INTO tbl_employee(last_name,email, gender) VALUES (#{lastName},#{email},#{gender})
    </insert>

 useGeneratedKeys="true"
 keyProperty="id" 
image.png
上一篇 下一篇

猜你喜欢

热点阅读