1.优点
2.缺点
1.核心jar包
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
2.配置mybatis扫描路径
@SpringBootApplication
@MapperScan(basePackages = {"com.xsh.springdemo"})
public class SpringdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringdemoApplication.class, args);
}
3.编写mapper文件 这里我没有使用xml形式,直接才用注解形式更方便简洁
public interface UserMapper extends Mapper<UserModel> {
@Insert("insert into test_user (name, address)value(#{user.name},#{user.address})")
@Options(useGeneratedKeys = true, keyProperty = "user.id", keyColumn = "id")
int addUser(@Param("user") UserModel user);
}
其中UserModel
内容
@Data
public class UserModel implements Serializable {
private Integer id;
private String name;
private String address;
public UserModel(String name, String address) {
this.name=name;
this.address=address;
}
}
test_user
表DDL
CREATE TABLE `test_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`address` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
4.编写单元测试用例
@Autowired
private UserMapper userMapper;
@Test
public void testAdd(){
UserModel userModel = new UserModel("测试姓名","测试地址");
userMapper.addUser(userModel);
System.out.println("主键为:"+userModel.getId());
}
调用实体的`getId`方法即可获取都记录的id值。