一、 Mapper接口
@Mapper
public interface ApiMapper {
//#{}有单引号,${}无单引号
@Insert("insert into tablel (id,name) values (${id},#{name})")
int insert(int id, String name);
@Select("select name from tablel where id = ( ${id} ) limit 1 ")
User select(int id);
@Delete("delete from tablel where name = #{n} ")
int delete(@Param("n") String name);
@Update("update tablel set name = #{name} where id = ${id}")
int update(int id, String name);
}
二、 service
@Service
public class ApiService {
@Autowired
ApiMapper apiMapper;
public String insert(int id, String name) {
try {
//若id为主键,且此id已经存在,则会报错
if (apiMapper.insert(id, name) > 0) {
return "success";
} else {
return "failed";
}
} catch (Exception e) {
return "数据库错误";
}
}
public User selectById(int id) {
return apiMapper.select(id);
}
public String deleteByName(String name) {
if (apiMapper.delete(name) > 0) {
return "success!!";
} else {
return "无此name";
}
}
public String update(int id, String name) {
if(apiMapper.update(id, name)>0){
return "success!!";
}else{
return "failed";
}
}
}
三、 controller
@RestController
public class ApiController {
@Autowired
ApiService apiService;
@PostMapping("/insert")
public String insert(@RequestParam int id,
@RequestParam(required = false, defaultValue = "zz") String name) {
return apiService.insert(id, name);
}
@GetMapping("/select")
public User selectById(@RequestParam(value = "id") int id) {
return apiService.selectById(id);
}
@RequestMapping("/delete")
public String deleteByName(@RequestParam String name) {
return apiService.deleteByName(name);
}
@RequestMapping("/update")
public String updateNameById(@RequestParam int id,
@RequestParam String name) {
return apiService.update(id, name);
}
}
小配置
mybatis:
configuration:
map-underscore-to-camel-case: true
Comments | 0 条评论