如何用注解的方式实现Mybatis插入数据时返回自增的主键Id

 更新时间:2022年07月04日 10:46:39   作者:Elon.Yang  
这篇文章主要介绍了如何用注解的方式实现Mybatis插入数据时返回自增的主键Id,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

用注解实现Mybatis插入数据返回自增的主键Id

我们在数据库表设计的时候,一般都会在表中设计一个自增的id作为表的主键。这个id也会关联到其它表的外键。

这就要求往表中插入数据时能返回表的自增id,用这个ID去给关联表的字段赋值。下面讲一下如何通过注解的方式实现插入数据时返回自增Id。

设计数据库表

CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  `age` int(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

设计Java bean对象

public class User
{
	private int userId = -1;
	private String name = "";
	
	private int age = -1;
	
	@Override
	public String toString()
	{
		return "name:" + name + "|age:" + age;
	}
	public int getUserId()
	{
		return userId;
	}
	public void setUserId(int userId)
	{
		this.userId = userId;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
}

添加mapper接口

@Mapper
public interface UserMapper
{
	@Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
	@Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="id")
	void insertUser(User user);
} 

通过以上几个步骤就可以实现在插入user到数据库时返回自增ID。数据插入成功后,id值被反填到user对象中,调用getUserId()就可以获取。

上面的写法有个地方需要注意一下: 如果insertUser使用了@Param注解,如:void insertUser(@Param(“user”) User user),keyProperty需要指定为 user.userId。

Mybatis注解增(返回自增id) 删查改以及(一对一,一对多,多对多)

数据库表

目录结构

导入坐标(包)

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
    </dependencies>

配置文件

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springboot
jdbc.username=root
jdbc.password=111111

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>
<!--    别名-->
    <typeAliases>
        <package name="com.zyw.domain"/>
    </typeAliases>
    <!--    注册自定义类型处理器-->
    <typeHandlers>
        <typeHandler handler="com.zyw.typeHandler.TypeHandler"/>
    </typeHandlers>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.zyw.mapper"/>
    </mappers>
</configuration>

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout

实体类

Order

package com.zyw.domain;
public class Order {
    private Integer id;
    private String ordername;
    private Integer ordernum;
    private User user;
    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", ordername='" + ordername + '\'' +
                ", ordernum=" + ordernum +
                ", user=" + user +
                '}';
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getOrdername() {
        return ordername;
    }
    public void setOrdername(String ordername) {
        this.ordername = ordername;
    }
    public Integer getOrdernum() {
        return ordernum;
    }
    public void setOrdernum(Integer ordernum) {
        this.ordernum = ordernum;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}

Role

package com.zyw.domain;
import java.util.List;
public class Role {
    private Integer id;
    private String roleName;
    private String roleDesc;
    private List<User> userList;
    public void setUser(List<User> userList) {
        this.userList = userList;
    }
    public List<User> getUser() {
        return userList;
    }
    @Override
    public String toString() {
        return "Role{" +
                "id=" + id +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                ", user=" + userList +
                '}';
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getRoleName() {
        return roleName;
    }
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
    public String getRoleDesc() {
        return roleDesc;
    }
    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }
}

User

package com.zyw.domain;
import java.util.Date;
import java.util.List;
public class User {
    private Integer id;
    private String username;
    private String email;
    private String password;
    private Long phoneNum;
    private Date birthday;
    private List<Order> orderList;
    public List<Order> getOrderList() {
        return orderList;
    }
    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    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 String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void setPhoneNum(Long phoneNum) {
        this.phoneNum = phoneNum;
    }
    public Long getPhoneNum() {
        return phoneNum;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", email='" + email + '\'' +
                ", password='" + password + '\'' +
                ", phoneNum=" + phoneNum +
                ", birthday=" + birthday +
                ", orderList=" + orderList +
                '}';
    }
}

mapper接口编写

OrderMapper

public interface OrderMapper {
    @Select("select * from orders ")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "ordername",property = "ordername"),
            @Result(column = "ordernum",property = "ordernum"),
            @Result(
                    property = "user",
                    column = "uid",
                    javaType = User.class,
                    one = @One(select = "com.zyw.mapper.UserMapper.findById")
            )
    })
    public List<Order> findAll();
    @Select("select * from orders where uid=#{uid}")
    public List<Order> findByUid(Integer uid);
}

RoleMapper

public interface RoleMapper {
    @Select("select * from sys_role")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "roleName",property = "roleName"),
            @Result(column = "roleDesc",property = "roleDesc"),
            @Result(
                    property = "userList",
                    column = "id",
                    javaType = List.class,
                    many = @Many(select = "com.zyw.mapper.UserMapper.findUserAndRoleById")
            )
    })
    public List<Role> findRoleAndUser();
}

UserMapper (注意自增id是返回到实体类)

public interface UserMapper {
    @Select("select * from sys_user")
    public List<User> findAll();
    @Select("select * from sys_user where id=#{id}")
    public User findById(Integer id);
    @Insert("insert into sys_user values(#{id},#{username},#{email},#{password},#{phoneNum},#{birthday})")
    @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
    public void insertUser(User user);
    @Update("update sys_user set password=#{password} where id=#{id}")
    public void updateUser(User user);
    @Delete("delete from sys_user where id=#{id}")
    public void deleteUser(Integer id);
    @Select("select * from sys_user")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "username",property = "username"),
            @Result(column = "password",property = "password"),
            @Result(column = "email",property = "email"),
            @Result(column = "phoneNum",property = "phoneNum"),
            @Result(column = "birthday",property = "birthday"),
            @Result(
                    property = "orderList", //封装的属性名称
                    column = "id", //根据哪个字段去查询order表中的数据
                    javaType = List.class, //返回类型
                    many = @Many(select = "com.zyw.mapper.OrderMapper.findByUid")
            )
    })
    public List<User> findUserAndOrder();
    @Select("select * from sys_user u,sys_user_role ur where u.id=ur.userId and ur.roleId=#{id}")
    public List<User> findUserAndRoleById(Integer id);
}

测试      

单表增删查改

AnnoTest

public class AnnoTest {
    private UserMapper mapper ;
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
         mapper=sqlSession.getMapper(UserMapper.class);
    }
    @Test
    public void testFindAll(){
        List<User> userList = mapper.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }
    @Test
    public void testFindById(){
        User byId = mapper.findById(1);
        System.out.println(byId);
    }
    @Test
    public void testInsertUser(){
        User user=new User();
        user.setUsername("小张");
        user.setPassword("951753");
        user.setPhoneNum(13449484984L);
        user.setEmail("951@qq.com");
        user.setBirthday(new Date());
        mapper.insertUser(user);
System.out.println(user.getId());
    }
    @Test
    public void testUpdateUser(){
        User user=new User();
        user.setId(1);
        user.setPassword("123456");
        mapper.updateUser(user);
    }
    @Test
    public void testDeleteUser(){
        mapper.deleteUser(9);
    }

一对一

AnnoTestOneToOne

public class AnnoTestOneToOne {
    private OrderMapper mapper ;
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        mapper=sqlSession.getMapper(OrderMapper.class);
    }
    @Test
    public void testDemo(){
        List<Order> orderList = mapper.findAll();
        for (Order order : orderList) {
            System.out.println(order);
        }
    }
}

一对多

AnnoTestOneToMany

public class AnnoTestOneToMany {
    private UserMapper mapper ;
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        mapper=sqlSession.getMapper(UserMapper.class);
    }
    @Test
    public void testDemo(){
        List<User> userList = mapper.findUserAndOrder();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

多对多

AnnoTestManyToMany

public class AnnoTestManyToMany {
    private RoleMapper mapper ;
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        mapper=sqlSession.getMapper(RoleMapper.class);
    }
    @Test
    public void testDemo(){
        List<Role> roleList = mapper.findRoleAndUser();
        for (Role role : roleList) {
            System.out.println(role);
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • springboot多环境进行动态配置的方法

    springboot多环境进行动态配置的方法

    这篇文章主要介绍了springboot多环境下如何进行动态配置,本文主要分享了如何在springboot的项目中使用多环境配置,重点是”spring.profiles.active“属性,需要的朋友可以参考下
    2022-06-06
  • 关于JSqlparser使用攻略(高效的SQL解析工具)

    关于JSqlparser使用攻略(高效的SQL解析工具)

    这篇文章主要介绍了关于JSqlparser使用攻略(高效的SQL解析工具),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • spring boot 学习笔记(入门篇)

    spring boot 学习笔记(入门篇)

    ing Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。这篇文章给大家带来了spring boot 入门学习笔记,需要的朋友参考下
    2018-02-02
  • Java字节流与基本数据类型的转换实例

    Java字节流与基本数据类型的转换实例

    本篇文章主要介绍了Java字节流与基本数据类型的转换实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • SpringBoot+Thymeleaf静态资源的映射规则说明

    SpringBoot+Thymeleaf静态资源的映射规则说明

    这篇文章主要介绍了SpringBoot+Thymeleaf静态资源的映射规则说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • 一篇文章带你入门Java UML的类图

    一篇文章带你入门Java UML的类图

    这篇文章主要为大家详细介绍了Java UML的类图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-02-02
  • 解读Spring配置文件中的property标签中的属性

    解读Spring配置文件中的property标签中的属性

    这篇文章主要介绍了Spring配置文件中的property标签中的属性,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • JEE与Spring Boot代码性能比较分析

    JEE与Spring Boot代码性能比较分析

    JavaEE与Spring Boot其实很难比较测试,前者适合单体SOA架构,后者适合微服务,但是还是有好事者把两者放在一起比较性能。这篇文章主要介绍了JEE与Spring Boot代码性能比较,需要的朋友可以参考下
    2018-11-11
  • Java内部类及其特点的讲解

    Java内部类及其特点的讲解

    今天小编就为大家分享一篇关于Java内部类及其特点的讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • spring boot上传文件出错问题如何解决

    spring boot上传文件出错问题如何解决

    这篇文章主要介绍了spring boot上传文件出错问题如何解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01

最新评论