1.引入第三方工具mybatis的场景启动器
y
如果有错误可以根据Ide提示修改
2.在resources下建立mybatis文件写入mybatis-config.xml全局配置文件
//开启驼峰命名规则
再在mybatis下建立mapper文件夹,放入AccountMapper.xml文件,用于映射操作数据库
select * from student where id = #{id}
3.在bean下写一个Acount类封装student表中的信息,如下
package com.ml.admin.bean;
import lombok.Data;
@Data
public class Account {
private Integer id;
private String name;
private Integer age;
}
4.在mapper文件下写一个AccountMapper接口操作数据表student表,如下
@Mapper
public interface AccountMapper {
public Account getAccount_id(Integer id);
}
5.在application.yaml中配置mybatis映射规则
mybatis: config-location: classpath:mybatis/mybatis-config.xml #全局配置文件路径 mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件路径
6.在service下创建AccountService.java文件用于实现AccountMapper接口,如下
package com.ml.admin.service;
import com.ml.admin.bean.Account;
import com.ml.admin.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AccountService {
@Autowired
AccountMapper accountMapper;
public Account get_by_id(Integer id) {
return accountMapper.getAccount_id(id);
}
}
7.使用@ResponseBody返回查询数据,代码如下
@Autowired
AccountService accountService;
@ResponseBody //用于返回json数据,要是没有这个页面就会解析错误
@GetMapping("/account")
public Account get_id(@RequestParam("id") Integer id){
return accountService.get_by_id(id);
}
student表
结果如下
mybatis:
#config-location: classpath:mybatis/mybatis-config.xml #全局配置文件路径
mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件路径
configuration: # 和上面的全局配置文件只能存在一个,所以可以删除mybatis-config.xml文件
map-underscore-to-camel-case: true
依旧访问正常



