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

目录
  • 用注解实现Mybatis插入数据返回自增的主键Id
    • 设计数据库表
    • 设计Java bean对象
    • 添加mapper接口
  • Mybatis注解增(返回自增id) 删查改以及(一对一,一对多,多对多)
    • 数据库表
    • 目录结构
    • 导入坐标(包)
    • 配置文件
    • 实体类
    • mapper接口编写
    • 测试

用注解实现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);
        }
    }
}

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

(0)

相关推荐

  • 详解mybatis插入数据后返回自增主键ID的问题

    1.场景介绍: ​开发过程中我们经常性的会用到许多的中间表,用于数据之间的对应和关联.这个时候我们关联最多的就是ID,我们在一张表中插入数据后级联增加到关联表中.我们熟知的mybatis在插入数据后返回的是插入成功的条数,那么这个时候我们想要得到相应的这条新增数据的ID,该怎么办呢? 2.插入数据返回自增主键ID方法(一) 在映射器中配置获取记录主键值xml映射: 在xml中定义useGeneratedKeys为true,返回主键id的值,keyProperty和keyColumn分别代表数据库

  • mybatis实现批量插入并返回主键(xml和注解两种方法)

    目录 mybatis批量插入并返回主键(xml和注解两种方法) mybatis批量插入 xml形式 注解形式 mybatis批量插入并返回主键笔记 mapper中的代码 xml中的代码,collection必须填list类型 mybatis批量插入并返回主键(xml和注解两种方法) mybatis批量插入 在mysql数据库中支持批量插入,所以只要配置useGeneratedKeys和keyProperty就可以批量插入并返回主键了. 比如有个表camera,里面有cameraNo,chanIn

  • Mybatis插入时返回自增主键方式(selectKey和useGeneratedKeys)

    目录 Mybatis插入时返回自增主键 Mybatis批量插入返回自增主键 解决办法 Mybatis插入时返回自增主键 通过selectKey在插入操作前或者操作后获取key值,做为字段插入或返回字段.(此段代码获取的序列值id作为字段值插入到实体类中返回) <insert id="insert"> <selectKey keyProperty="id" resultType="int" order="AFTER&qu

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

    目录 用注解实现Mybatis插入数据返回自增的主键Id 设计数据库表 设计Java bean对象 添加mapper接口 Mybatis注解增(返回自增id) 删查改以及(一对一,一对多,多对多) 数据库表 目录结构 导入坐标(包) 配置文件 实体类 mapper接口编写 测试 用注解实现Mybatis插入数据返回自增的主键Id 我们在数据库表设计的时候,一般都会在表中设计一个自增的id作为表的主键.这个id也会关联到其它表的外键. 这就要求往表中插入数据时能返回表的自增id,用这个ID去给关联

  • 详解mysql插入数据后返回自增ID的七种方法

    引言 mysql 和 oracle 插入的时候有一个很大的区别是: oracle 支持序列做 id: mysql 本身有一个列可以做自增长字段. mysql 在插入一条数据后,如何能获得到这个自增 id 的值呢? 一:使用 last_insert_id() SELECT LAST_INSERT_ID(); 1. 每次 mysql 的 query 操作在 mysql 服务器上可以理解为一次"原子"操作, 写操作常常需要锁表, 这里的锁表是 mysql 应用服务器锁表不是我们的应用程序锁表

  • Mybatis批量插入返回插入成功后的主键id操作

    我们都知道Mybatis在插入单条数据的时候有两种方式返回自增主键: 1.对于支持生成自增主键的数据库:增加 useGenerateKeys和keyProperty ,<insert>标签属性. 2.不支持生成自增主键的数据库:使用<selectKey>. 但是怎么对批量插入数据返回自增主键的解决方式网上看到的还是比较少,至少百度的结果比较少. Mybatis官网资料提供如下: First, if your database supports auto-generated key

  • Mybatis执行插入语句后并返回主键ID问题

    目录 1.MySQL数据库设置ID自增情况 2.使用UUID自增主键 3.mybatis-plus在执行插入语句后返回自定义ID 总结 我们知道JDBC可以实现插入语句后返回主键Id,那mybatis可以实现吗? 答案是肯定的. 1.MySQL数据库设置ID自增情况 <insert id="insertUser" parameterType="com.crush.mybatisplus.entity.User"> INSERT INTO tb_user

  • MyBatis insert操作插入数据之后返回插入记录的id

    MyBatis插入数据的时候,返回该记录的id <insert id="insert" keyProperty="id" useGeneratedKeys="true"
 parameterType="com.demo.domain.CountRateConfig">
 insert into query_rate_config (code,partner_type,search_count, booking_co

  • Mybatis实现插入数据后返回主键过程解析

    添加记录后获取主键ID,这是一个很常见的需求,特别是在一次前端调用中需要插入多个表的场景. 除了添加单条记录时获取主键值,有时候可能需要获取批量添加记录时各记录的主键值,MyBatis从3.3.1版本开始支持批量添加记录并返回各记录主键字段值. 一.获取新添加记录主键字段值 注意: 在MyBatis中添加操作返回的是记录数并非记录主键id. 如果需要获取新添加记录的主键值,需要在执行添加操作之后,直接读取Java对象的主键属性. Integer rows = sqlSession.getMapp

  • MyBatis在insert插入操作时返回主键ID的配置(推荐)

    很多时候,在向数据库插入数据时,需要保留插入数据的id,以便进行后续的update操作或者将id存入其他表作为外键. 但是,在默认情况下,insert操作返回的是一个int值,并且不是表示主键id,而是表示当前SQL语句影响的行数... 接下来,我们看看MyBatis如何在使用MySQL和Oracle做insert插入操作时将返回的id绑定到对象中. MySQL用法: <insert id="insert" parameterType="com.test.User&qu

  • Mybatis 插入一条或批量插入 返回带有自增长主键记录的实例

    首先讲一下, 插入一条记录返回主键的 Mybatis 版本要求低点,而批量插入返回带主键的 需要升级到3.3.1版本,3.3.0之前的都不行. <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.3.1</version> </dependency> 1.MySQL <

随机推荐