Mybatis @Insert插入数据返回自增的主键id

Mybatis @Insert插入数据返回Mysql自增的主键id

采用的是spring+mybatis+mysql,id是自增的

第一种方案

public interface UserInfoDao {
	
	@Insert("insert into user_info(name,age,gender,telephone,register_mode) values(#{name}, #{age}, #{gender}, #{telephone}, #{registerMode}) ")
	@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
	void insertUserInfo(UserInfo userInfo);
}

userInfo.getId()

第二种方案

public interface UserInfoDao {
	@Insert("insert into user_info(name,age,gender,telephone,register_mode) values(#{name}, #{age}, #{gender}, #{telephone}, #{registerMode}) ")
	@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = int.class)
	void insertUserInfo(UserInfo userInfo);
}

userInfo.getId()

测试类

@RunWith(SpringRunner.class) 
@SpringBootTest
@Slf4j
public class UserInfoDaoTest {
	
	@Autowired
	private UserInfoDao userInfoDao;
	
	@Test
	public void testInsertUserInfo() {
		UserInfo userInfo = new UserInfo();
		userInfo.setTelephone("13110472186");
		userInfo.setName("asd");
		userInfo.setAge(30);
		userInfo.setGender((short)1);
		userInfo.setRegisterMode("byPhone");
		userInfoDao.insertUserInfo(userInfo);
		
		log.info("id={}",userInfo.getId());
		//log.info("userInfo={}",userInfo);
	}

}

你可能感兴趣的:(SpringBoot)