MyBatis基于注解数据库插入记录后返回自增编号

MyBatis基于注解数据库插入记录后返回自增编号

  在使用SSM框架完成数据库新增记录任务时,经常遇到新增记录的主键是自增int类型,因此需要插入后立即获得其id再执行接下来的操作,下面给出一个亲测有效的方案:

传统办法

  如果是小型应用或单用户的程序,可以重新根据插入的记录执行一次查询操作,或直接执行"Select MAX(id)"。但这些办法十分不稳定,不适用。

注解方式获得自增编号

  假设插入一个博文(数据库mysql表为blog),博文的主键为blogid。
(1)编写JavaBean:

public class Blog {
	private int blogid;
	...
	
	public int getBlogid() {
		return blogid;
	}
	public void setBlogid(int blogid) {
		this.blogid = blogid;
	}
	...

(2)MyBatis的Mapper接口

	@Insert("insert into blog(blogimg, userid, title, content, type, reprinted, state, resource, uptime,"
			+ "difficult, istop) values(#{blog.blogimg}, #{blog.userid}, #{blog.title}, #{blog.content}, "
			+ "#{blog.type}, #{blog.reprinted}, #{blog.state}, #{blog.resource}, #{blog.uptime}, "
			+ "#{blog.difficult}, #{blog.istop})")
	@Options(useGeneratedKeys=true, keyProperty="blog.blogid")
	void addNewBlog(@Param("blog") Blog blog);

注意,使用@Param时,需要指定对象,keyProperty中为待获得的主键blogid。

(3)Service服务端接口的实现方法

    @Override
	public void addNewBlog(String blogimg, String userid, String title, String content, 
			String type, String reprinted, String state, String resource, String uptime, String difficult,
			String istop, int blogid) {
		//创建一个Blog对象,将插入的值set到对象中
		Blog blog = new Blog();
		blog.setBlogimg(blogimg);
		blog.setUserid(userid);
		blog.setTitle(title);
		blog.setContent(content);
		blog.setType(type);
		blog.setReprinted(reprinted);
		blog.setState(state);
		blog.setResource(resource);
		blog.setUptime(uptime);
		blog.setDifficult(difficult);
		blog.setIstop(istop);
		
		//对应的MaBatis的Mapper接口
		blogMapper.addNewBlog(blog);
		
		//在此可以获得插入记录的自增id
		System.out.print("blog.getBlogid()=" + blog.getBlogid());
	}

当成功插入记录时,MyBatis将会把自增id自动set到传入的对象blog中,直接get出来即可。

发布了96 篇原创文章 · 获赞 158 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36426650/article/details/104359726