你可以通过Spring Initializr添加MyBatis的Starer。
JavaBean:
package com.wzy.springbootmybatis.pojo;
@Data //Getter、Setter方法
@NoArgsConstructor//无参构造器
@AllArgsConstructor//全参构造器
public class Person {
private Integer id;
private String username;
private String gender;
private Integer age;
private String phone;
}
Dao接口:在接口使用@Mapper注释。或者在启动类上使用@MapperScan(“com.wzy.springbootmybatis.dao”)扫描接口。
package com.wzy.springbootmybatis.dao;
@Mapper
public interface PersonDao {
public Person getPesonOne(Integer id);
//注解版的查询
@Select("select id,username,gender,age,phone from person where id=#{id}")
public Person getPesonOne2(Integer id);
//sql文件配置版的插入
public int insertPerson(Person person);
//注解版的插入,不需要在sql配置文件内写sql语句。
//@Options是 @Insert胡配置注解.useGeneratedKeys="true":使用自增主键,keyProperty="id":自增主键在javaBean中的变量名
//
@Insert("insert into person(username,gender,age,phone) values (#{username},#{gender},#{age},#{phone})")
@Options(useGeneratedKeys = true,keyProperty = "id")//可以获取插入的id
public int insertPerson2(Person person);
}
Service层:
package com.wzy.springbootmybatis.service;
@Service
public class PersonServlce {
@Autowired
PersonDao personDao;
public Person getSelectPersonOne(Integer id){
return personDao.getPesonOne(id);
}
public Person getSelectPersonOne2(Integer id){
return personDao.getPesonOne2(id);
}
public int insertPersonOne(Person person){
return personDao.insertPerson(person);
}
public int insertPersonOne2(Person person){
return personDao.insertPerson2(person);
}
}
controller:
package com.wzy.springbootmybatis.controller;
@Controller
public class PerosnController {
@Autowired
PersonServlce personServlce;
@ResponseBody
@RequestMapping(value = "/person",method = RequestMethod.GET)
public Person getPerson(@RequestParam("id") Integer id){
return personServlce.getSelectPersonOne(id);
}
@ResponseBody
@RequestMapping(value = "/person2",method = RequestMethod.GET)
public Person getPerson2(@RequestParam("id") Integer id){
return personServlce.getSelectPersonOne2(id);
}
@ResponseBody
@RequestMapping(value = "/insertperson",method = RequestMethod.POST)
public Person insertPerson1(Person person){//自动封装
int i = personServlce.insertPersonOne(person);//插入数据
return person;//返回插入的数据
}
@ResponseBody
@RequestMapping(value = "/insertperson2",method = RequestMethod.POST)
public Person insertPerson2(Person person){//自动封装
int i = personServlce.insertPersonOne2(person);//插入数据
return person;//返回插入的数据
}
}
启动类:使用@MapperScan("com.lun.boot.mapper")
简化,Mapper接口就可以不用标注@Mapper
注解。
package com.wzy.springbootmybatis;
//@MapperScan("com.wzy.springbootmybatis.dao")
@SpringBootApplication
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}