主键字段的处理:
利用数据自增列作为主键时,执行insert操作时,可以在服务器端自动获取主键值
-Mysql中创建表:create table t_emp(id int primary key auto_increment,name varchar(20),age int)
在Mysql中查看数据结构:
----------------------------------------------------------------
Dao接口:
package cn.tedu.cloud_note.dao;
import cn.tedu.cloud_note.entity.Emp;
public interface EmpDao {
public void save(Emp emp);//用于测试自增主键
}
----------------------------------------------------------------
Mapper文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<!-- 用于测试自增主键 id-->
<mapper namespace="cn.tedu.cloud_note.dao.EmpDao">
<!-- Mysql:数据库自动生成主键,获取主键放入emp对象的id属性中 若要获取该主键
则需要添加两个属性useGeneratedKeys="true"和keyProperty="主键的属性"-->
<insert id="save"
parameterType="cn.tedu.cloud_note.entity.Emp"
useGeneratedKeys="true" keyProperty="id">
insert into t_emp (name,age) values (#{name},#{age})
</insert>
</mapper>
----------------------------------------------------------------
测试代码:
package test.dao;
import org.junit.Before;
import org.junit.Test;
import cn.tedu.cloud_note.dao.EmpDao;
import cn.tedu.cloud_note.entity.Emp;
import test.TestBase;
public class TestEmpDao extends TestBase{
private EmpDao dao;
@Before
public void init(){
dao = super.getContext().getBean("empDao",EmpDao.class);
}
@Test//用于测试自增主键,保存一个Emp对象到数据库,返回自增列的值
public void testSave(){
Emp emp = new Emp();
emp.setName("莉莉丝");
emp.setAge(25);
dao.save(emp);
int id = emp.getId();
System.out.println("刚插入的ID:"+ id);
System.out.println(emp);
}
}
----------------------------------------------------------------
测试结果:
刚插入的ID:3
Emp [id=3, name=莉莉丝, age=25]
Emp [id=3, name=莉莉丝, age=25]
注意:若不需要返回自增列的值,则Mapper文件中insert标签可以不使用最后两个属性