SpringBoot整合mybatis的兩種方式
簡單方法
1.定義實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
Integer id;
String name;
String gender;
String address;
}
2.定義接口 在接口中使用注解實作SQL語句
@Mapper
public interface UserMapper {
@Select("select * from student_info")
List<User> getAll();
@Select("select * from student_info where id=#{id}")
User getById(Integer id);
}
3.定義service層和controller層調用
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public List<User> getAllUser(){
return userMapper.getAll();
}
public User getUserById(Integer id){
return userMapper.getById(id);
}
}
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/user/all")
List<User> getAllUser(){
return userService.getAllUser();
}
@GetMapping("/user/{id}")
User getUser(@PathVariable("id") Integer id){
return userService.getUserById(id);
}
}
複雜方法
1.定義實體類
@Data
public class Product {
Integer id;
String name;
Double price;
String description;
}
2.定義接口
@Mapper
public interface ProductMapper {
List<Product> getAllProduct();
}
3.定義相應的xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lp.student.mapper.ProductMapper">
<resultMap id="BaseResultMap" type="com.lp.student.entity.Product">
<result column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="price" jdbcType="DOUBLE" property="price"/>
<result column="description" jdbcType="VARCHAR" property="description"/>
</resultMap>
<select id="getAllProduct" resultType="com.lp.student.entity.Product">
select * from product;
</select>
</mapper>
在application.yaml中定義包掃描的位置
mybatis:
mapper-locations: classpath*:/mapper/*Mapper.xml
在主啟動類上加上注解 開啟掃描
@MapperScan("com.lp.student.mapper")
@MapperScan("com.lp.student.mapper")
@SpringBootApplication
public class StudentApplication {
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}
4.定義service層和controller層進行調用
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
ProductMapper productMapper;
@Override
public List<Product> getAllProduct() {
return productMapper.getAllProduct();
}
}
@RestController
public class ProductController {
@Autowired
ProductService productService;
@GetMapping("/product/all")
List<Product> getAllProduct(){
return productService.getAllProduct();
}
}