实体类
@Data
@NoArgsConstructor
public class Phone {
private int id;
private String brand; // 品牌
private String model; // 型号
private int salary; // 价格
}
mapper接口和sql
useGeneratedKeys=“true” , keyProperty位实体类字段,用来存储自增id
<insert id="insertPhone" parameterType="phone" useGeneratedKeys="true" keyProperty="id">
insert into phone(brand, model, salary) values(#{brand}, #{model}, #{salary})
</insert>
测试
通过以上参数设置后自增id就会赋值给实体类的属性id,通过get就可直接拿到
@SpringBootTest
public class PhoneTest {
@Autowired
private UserInfoMapper userInfoMapper;
@Test
public void test() {
Phone phone = new Phone();
phone.setBrand("努比亚");
int num = userInfoMapper.insertPhone(phone);
System.out.println("id = " + phone.getId());
Assertions.assertEquals(1, num);
}
}