优点:1.mybatis-plus这样一个框架,一种集mybatis与hibernate的优点一起的框架。它提供了hibernate的单表CRUD操作的方便同时,又保留了mybatis的特性。
2.内置sql注入玻璃器,有效防止sql注入
3.多种主键策略,可以自由配置,完美解决主键问题
4.支持代码自动生成三层
5.内置分页插件
例子:
使用RestFul api :
1.查单个:
User user =iUserService.selectOne(new EntityWrapper<>());
2.查List<对象>
/**
* http://localhost:8083/user
* @return
*/
@GetMapping
public List<User> getList()
{
List<User> list=iUserService.selectList(new EntityWrapper<>());
return list;
}
3.分页
/**
* 分页 传http://localhost:8083/user/selectListByPage?current=1&size=3
*/
@GetMapping("/selectListByPage")
public Page selectListByPage(Page page){
Page p =new Page(page.getCurrent(),page.getSize());
p = iUserService.selectPage(p,new EntityWrapper<>());
return p;
}
4.在查询中添加枚举
/**
* 在查询中添加枚举
*/
@GetMapping("/selectByEnum")
public Page selectByEnum(Page page){
Page p =new Page(page.getCurrent(),page.getSize());
p = iUserService.selectPage(p,new EntityWrapper<>());
List<User> list= p.getRecords();
for (User i:list)
{
i.setState(UserStateEnum.getDescByCode(i.getState()));
}
return p;
}
5.按id查
/**
* 按id查
* http://localhost:8083/user/6
* 不写@PathVariable 获取不到参数
* @param id
* @return
*/
@GetMapping("/{id}")
@ApiOperation(value = "用户查询服务")
public User getUserById(@ApiParam("用户id") @PathVariable Long id){
System.out.println("进入getUserById方法...");
System.out.println("id="+id);
User user =iUserService.selectById(id);
return user;
}
6.按条件查
/**
*使用自定义返回类
* 按name查
* http://localhost:8083/user/getUserByName?name=猪瑾
* @param name
* @return
*/
@GetMapping("/getUserByName")
public Result getUserByName(String name)
{
System.out.println(name);
System.out.println("name="+ name);
User user= iUserService.selectOne(new EntityWrapper<User>().eq("name",name));
return ResultUtil.success(user);
}
7.新增
/**
* Result api 新增
* validation.constraints包下
* @Valid+BindingResult判断输入信息是否合法
* BindingResult封装错误信息
* http://localhost:8083/user post方式 bady->raw写对象{"xx":""xx,}
* @RequestBody必须要加 不然获取不到参数
* @param user
* @return
*/
@PostMapping
public Result insertUser(@Valid @RequestBody User user, BindingResult erros) {
System.out.println("1:" + user.getName());
//经过校验判断对象里面有没有错 有错 ture
if (erros.hasErrors()) {
erros.getAllErrors().stream().forEach(error ->{
FieldError fieldError =(FieldError) error;
msg=fieldError.getField()+" "+error.getDefaultMessage();
// System.out.println(msg);循环打出错误信息
});
//把错误信息装到ResultUtil中
return ResultUtil.error(900,msg);
}
//获取当前时间戳
Long timechuo = Instant.now().toEpochMilli();
System.out.println("时间戳:" + timechuo);
user.setTime(timechuo.toString());
System.out.println(user);
Boolean ids = iUserService.insert(user);
System.out.println(ids);
if (ids) {
return ResultUtil.success(user);
}
return ResultUtil.error(8, "新增失败!");
}
实体类:
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@NotBlank
@ApiModelProperty("用户姓名")
private String name;
@NotBlank
private String state;
private String time;
}
9.修改
/**
* 修改用户
* 如需参数校验 请模仿新增
* @return
*/
@PutMapping
public Result updateUser(@RequestBody User user)
{
System.out.println(user);
if(user.getId()==null)
{
return ResultUtil.error(92,"id不能为空");
}
else {
Boolean isSe =iUserService.updateById(user);
if (isSe)
{
return ResultUtil.success(user);
}
else
{
return ResultUtil.error(12,"修改失败!");
}
}
}
10.删除
**
* 删除
* @param id
* http://localhost:8083/user/3
* @return
*/
@DeleteMapping("/{id}")
public Result deleteUser(@PathVariable Integer id)
{
System.out.println(id);
Boolean isSe =iUserService.deleteById(id);
if (isSe)
{
return ResultUtil.success();
}
return ResultUtil.error(23,"删除失败!");
}
11.按条件查(多条件 可能为空 拼接sql)
1)dao
public interface AccountMapper extends BaseMapper<Account> {
//手工调涨
@Select("SELECT DISTINCT\n" +
"\t(c.merchant_name),\n" +
"\ta.create_time AS createtime,\n" +
"\ta.last_operate_amount AS lastoperateamount,\n" +
" a.last_operate_type AS lastoperatetype,\n" +
" a.acount_amount as acountamount,\n" +
" b.apply_status as applystatus,\n" +
" a.remark as remark,\n" +
" b.apply_name as applyname,\n" +
" b.examine_name as examinename\n" +
"FROM\n" +
"\taccount a\n" +
"LEFT JOIN account_apply b ON a.account_id = b.account_id\n" +
"LEFT JOIN product_business c ON a.merchant_code = c.merchant_id" +
"${merchantnamesql}${lastoperatetypesql}${startsql}${endsql}")
List<Map> selectList(@Param("merchantnamesql")String merchantnamesql,@Param("lastoperatetypesql")String lastoperatetypesql,@Param("startsql")String startsql,@Param("endsql")String endsql);
}
2):service
public interface IAccountService extends IService<Account> {
List<Map> selectList(String merchantname,String lastoperatetype,String start,String end);
}
3:serviceimpl
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public List<Map> selectList(String merchantname, String lastoperatetype, String start, String end) {
String merchantnamesql="";
String lastoperatetypesql="";
String startsql="";
String endsql="";
if(merchantname!=null)
{
merchantnamesql=" WHERE c.merchant_name="+merchantname;
}
if(lastoperatetype!=null)
{
lastoperatetypesql="AND a.last_operate_type="+lastoperatetype;
}
if(start!=null&& end!=null)
{
startsql="AND a.sys_date BETWEEN"+start;
endsql="AND"+end;
}
List<Map> list=accountMapper.selectList(merchantnamesql,lastoperatetypesql,startsql,endsql);
return list;
}
}
4.controller
@RestController
@RequestMapping("/accountController")
public class AccountController {
@Autowired
private IAccountService iAccountService;
//手工调账查询
@RequestMapping("/select")
public Page selectList(Page page, String merchantname,String type, String start,String end){
Page p =new Page(page.getCurrent(),page.getSize());
List<Map> list = iAccountService.selectList(merchantname,type,start,end);
p.setRecords(list);
return p;
}
}
12: in查
List<ProductInfo> productInfo =iProductInfoService.selectList(new EntityWrapper<ProductInfo>().in("product_id",productIdList));
test测试: productInfoController.ListForOrder(Arrays.asList(1,2));
14:mybatis其他查询:
查询方式
说明
setSqlSelect
设置 SELECT 查询字段
where
WHERE 语句,拼接 + WHERE 条件
and
AND 语句,拼接 + AND 字段=值
andNew
AND 语句,拼接 + AND (字段=值)
or
OR 语句,拼接 + OR 字段=值
orNew
OR 语句,拼接 + OR (字段=值)
eq
等于=
allEq
基于 map 内容等于=
ne
不等于<>
gt
大于>
ge
大于等于>=
lt
小于<
le
小于等于<=
like
模糊查询 LIKE
notLike
模糊查询 NOT LIKE
in
IN 查询
notIn
NOT IN 查询
isNull
NULL 值查询
isNotNull
IS NOT NULL
groupBy
分组 GROUP BY
having
HAVING 关键词
orderBy
排序 ORDER BY
orderAsc
ASC 排序 ORDER BY
orderDesc
DESC 排序 ORDER BY
exists
EXISTS 条件语句
notExists
NOT EXISTS 条件语句
between
BETWEEN 条件语句
notBetween
NOT BETWEEN 条件语句
addFilter
自由拼接 SQL
last 拼接在最后,例如:last("LIMIT 1")