spring boot整合mybatis使用注解得到自增主键返回值

spring boot整合mybatis得到自增主键返回值

实体类

@Data
public class OrderRecord {

    private int applicantId;
    private String reason;
    private String members;
    private String startTime;
    private String endTime;
    private int flag;
    private int state;
    private int roomId;
    private int recordId;
    private int departmentId;
    private int companyId;
}

Mapper接口

public interface SimpleUserMapper {

    @Insert("insert into order_record(applicant_id,reason,members,start_time,end_time,room_id,state,department_id,company_id) values(#{applicantId},#{reason},#{members},#{startTime},#{endTime},#{roomId},#{state},#{departmentId},#{companyId})")
    @Options(useGeneratedKeys = true,keyProperty = "recordId")
    int addRecord(OrderRecord orderRecord);
}

useGeneratedKeys设为true是表示使用jdbc的getGeneratedKeys方法来取出数据的主键值(默认为false)

keyProperty标记返回的主键值传递给某个具体的属性(本例是将返回的值重新封装给recordId)

测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class ManagementApplicationTests {

	@Autowired
	private SimpleUserMapper simpleUserMapper;

	@Test
	public void contextLoads() throws UnsupportedEncodingException {
        
		OrderRecord orderRecord = new OrderRecord();
		orderRecord.setApplicantId(1);
		System.out.println(orderRecord.getRecordId());
		simpleUserMapper.addRecord(orderRecord);
		System.out.println(orderRecord.getRecordId());

	}

测试结果

在这里插入图片描述

你可能感兴趣的:(mybatis,Spring,Boot)