Mysql方式如下:
配置文件如下:
#mapper分离的位置
mybatis.mapper-locations=classpath:/mapper/*.xml
#mybatis别名搜索的位置, 例如参数中有cn.henu.pojo.User类型,配置别名可直接使用User代替上面的详细路径
mybatis.type-aliases-package=cn.henu.pojo
注意:数据库中对应的字段需要设置成自增生成:
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
`student_name` varchar(255) DEFAULT NULL,
`student_age` int NOT NULL,
`student_id` int NOT NULL AUTO_INCREMENT,
`student_teacher` varchar(255) DEFAULT NULL,
`student_detail` text,
PRIMARY KEY (`student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=227 DEFAULT CHARSET=utf8;
例如上面 student_id 字段 需要加上 AUTO_INCREMENT
在navicat中查看表的设计,选择对应字段可以看到自动递增被选择了。
Dao层
接口:
int insertAutoId(TStudent student);
xml文件:
<!--由于配置了别名,这里parameterType直接使用别名,不用写完整路径了-->
<insert id="insertAutoId" parameterType="TStudent" useGeneratedKeys="true" keyProperty="studentId" keyColumn="student_id">
insert into t_student (student_id, student_name, student_age,
student_teacher, student_detail)
values (#{studentId,jdbcType=INTEGER}, #{studentName,jdbcType=VARCHAR}, #{studentAge,jdbcType=INTEGER},
#{studentTeacher,jdbcType=VARCHAR}, #{studentDetail,jdbcType=LONGVARCHAR})
</insert>
注意:其中keyProperty是Java对象的属性名,keyColumn为数据库中的字段名,其实只要上面在设计表的时候主键使用了自增策略,选中了主键自增,就可以在插入的时候不添加主键字段,数据库会自动使用自增策略加入,只是无法在添加的同时获取到主键。
Service层
这里直接给出serviceImpl
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private TStudentMapper tStudentMapper;
@Override
public int addStudentAutoId(TStudent student) {
return tStudentMapper.insertAutoId(student);
}
}
Controller层
@RequestMapping("/addStudent")
@ResponseBody
public String insertStudent(){
// 这里我们不设置id,让其使用自增策略自动插入
TStudent tStudent = new TStudent();
tStudent.setStudentAge(10);
tStudent.setStudentDetail(new Date().toString());
studentService.addStudentAutoId(tStudent);
//返回刚刚插入的id,如果上文xml文件中没有加入那两个属性,这里无法获取到
return tStudent.getStudentId()+"";
}
Oracle方式如下:
<insert id="addClass" parameterType="cn.henu.pojo.Tclass">
<!-- 注意这里使用的是selectKey的方式设置主键自增,而且还会返回自增主键的值,还有一种序列的方式也可以做到 -->
<selectKey keyProperty="tid" resultType="int" order="BEFORE">
select nvl(max(TID),0)+1 from TCLASS
</selectKey>
<!-- 注意nvl(max(表中主键的名称),0)+1 from 表名 -->
INSERT INTO TCLASS
VALUES(#{imgfile},#{classes},#{tname},#{tnumber},#{tphone},#{temail},#{details},#{tid})
</insert>
扩展
mysql> SELECT LAST_INSERT_ID();
每次mysql_query操作在mysql服务器上可以理解为一次“原子”操作, 写操作常常需要锁表的, 是mysql应用服务器锁表不是我们的应用程序锁表。
值得注意的是,如你一次插入了多条记录,这个函数返回的是第一个记录的ID值。
因为LAST_INSERT_ID是基于Connection的,只要每个线程都使用独立的Connection对象,LAST_INSERT_ID函数 将返回该Connection对AUTO_INCREMENT列最新的insert or update*作生成的第一个record的ID。这个值不能被其它客户端(Connection)影响,保证了你能够找回自己的 ID 而不用担心其它客户端的活动,而且不需要加锁。使用单INSERT语句插入多条记录, LAST_INSERT_ID返回一个列表。
LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。
方法二:是使用max(id)
使用last_insert_id是基础连接的,如果换一个窗口的时候调用则会一直返回10
如果不是频繁的插入我们也可以使用这种方法来获取返回的id值
select max(id) from user;
这个方法的缺点是不适合高并发。如果同时插入的时候返回的值可能不准确。
方法三:是创建一个存储过程,在存储过程中调用先插入再获取最大值的操作
DELIMITER $$
DROP PROCEDURE IF EXISTS `test` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `test`(in name varchar(100),out oid int)
BEGIN
insert into user(loginname) values(name);
select max(id) from user into oid;
select oid;
END $$
DELIMITER ;
call test('gg',@id);
方法四:使用@@identity
select @@IDENTITY
方法五:是使用getGeneratedKeys()
Connection conn = ;
Serializable ret = null;
PreparedStatement state = .;
ResultSet rs=null;
try {
state.executeUpdate();
rs = state.getGeneratedKeys();
if (rs.next()) {
ret = (Serializable) rs.getObject(1);
}
} catch (SQLException e) {
}
return ret;
总结一下,在mysql中做完插入之后获取id在高并发的时候是很容易出错的。另外last_insert_id虽然是基于session的但是不知道为什么没有测试成功。
方法6:selectkey:
其实在ibtias框架里使用selectkey这个节点,并设置insert返回值的类型为integer,就可以返回这个id值。
像Oracle这样取序列的情况,需要设置为before,否则会报错。
另外在用Spring管理事务时,SelectKey和插入在同一事务当中,因而Mysql这样的情况由于数据未插入到数据库中,所以是得不到自动增长的Key。取消事务管理就不会有问题。
<insert id="insert" parameterType="map">
insert into table1 (name) values (#{name})
<selectKey resultType="java.lang.Integer" keyProperty="id">
CALL IDENTITY()
</selectKey>
</insert>
上面xml的传入参数是map,selectKey会将结果放到入参数map中。用POJO的情况一样,但是有一点需要注意的是,keyProperty对应的字段在POJO中必须有相应的setter方法,setter的参数类型还要一致,否则会报错。
@Insert("insert into table2 (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="nameId", before=false, resultType=int.class)
int insertTable2(Name name);
1.在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名,而不是表格的字段名。
<insert id="insert" parameterType="Spares"
useGeneratedKeys="true" keyProperty="id">
insert into system(name) values(#{name})
</insert>
int count = systemService.insert(systemBean);
int id = systemBean.getId(); //获取到的即为新插入记录的ID
1.Mybatis Mapper 文件中,“useGeneratedKeys”和“keyProperty”必须添加,而且keyProperty一定得和java对象的属性名称一直,而不是表格的字段名
全部评论