spring boot 訪問 MySQL
方式三:spring boot + mybaits
創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供河南網站建設、河南做網站、河南網站設計、河南網站制作等企業(yè)網站建設、網頁設計與制作、河南企業(yè)網站模板建站服務,10年河南做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。
pom 文件引入 依賴
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
mysql
mysql-connector-java
配置mybaits
# 對應實體類的包名
mybatis.typeAliasesPackage=com.example.demo.model
# mapper.xml文件所在位置
mybatis.mapperLocations=classpath:**/mapper/*.xml
加入 entity mapper service controller 文件
entity
public class User {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
private String sex;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
mapper
@Mapper
public interface UserMapper {
User findUserById(Long id);
int add(User user);
int update(User user);
}
xml
insert into user (name,age,sex) values (#{name},#{age},#{sex})
update user set name = #{name} ,age = #{age} ,sex = #{sex} where id = ${id}
service
@Service
public class MybatisUserService {
@Autowired
UserMapper userDao;
public int add(User user){
return userDao.add(user);
}
public int update(User user){
return userDao.update(user);
}
public User getById(long id){
return userDao.findUserById(id);
}
}
controller
@RestController
@RequestMapping("/mybatisUser")
public class MybatisUserController {
@Autowired
MybatisUserService userService;
@RequestMapping(value = "/add",method = RequestMethod.POST)
public Object addUser(@RequestBody User user){
return userService.add(user);
}
@RequestMapping(value = "/update",method = RequestMethod.PUT)
public Object updateUser(@RequestBody User user){
return userService.update(user);
}
@RequestMapping(value = "/find",method = RequestMethod.GET)
public Object updateUser(long id){
return userService.getById(id);
}
}
主類上加掃描 mapper 路徑
@SpringBootApplication
@MapperScan("com.example.demo.dao.mybatis")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
啟動項目 測試