现今的框架真的是越来越简洁了,项目搭建起来之后只用写个后台https://start.spring.io/,甚至连SQL都用不到了,这次的springboot+mybits-plus+mysql框架是项目开发是刚刚用到的,搬砖贼好用,推荐给各位码员。
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("jobob");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("密码");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.baomidou.ant");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
strategy.setInclude(scanner("表名"));
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
1,查看实体类,设置主键自动生成
@Data
@TableName("user")
public class User(){
/**
* ID主键
*/
@TableId(value = "id", type = IdType.UUID)
private String id;
/**
* 名称
*/
private String name;
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
}
2,Controller层注解
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController(){
@Autowired
private UserService userService;
/**
* 保存
* @param User user;
* /
@PostMapping("/save")
public Boolean save(@RequestBody User user){
userService.save();
return true;
}
/**
* 分页查询
* /
@PostMapping("/list")
public Ipage list(@RequestBody UserVo userVo){
IPage userList = userService.list(userVo);
return userList;
}
@PostMapping("/info")
public Ipage save( @RequestBody Map map){
User user = userService.getinfo(map.get("id"));
return user;
}
@PostMapping("/update")
public Boolean update( @RequestBody User user){
return userService.update(user);
}
@PostMapping("/delete")
public Boolean delete( @RequestBody Map map){
return userService.delete(map.get("id"));
}
@PostMapping("/exist")
public Boolean exist( @RequestBody Map map){
return userService.exist(map.get("name"));
}
}
3,serivce层
public interface userService extends IService {
/**
* 新增/编辑
* @param User
* @return
*/
Boolean save(User user);
}
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl implements userService {
@Autowired
private UserMapper userMapper;
/**
* 新增/编辑
*/
@Override
Boolean save(User user){
return true;
}
}
4,Dao/Mapper层
@Repository
public interface UserMapper extends BaseMapper {
/**
* 搜索信息列表
*/
List all(@Param("id") List id);
}
5,重点讲解QueryWrapper
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq(User.ID, Id);
List List = userService.list(queryWrapper);
List List = userMapper.list(queryWrapper);
service/mapper CRUD接口以及wapper条件构造器方法
@Select("select * from mysql_data ${ew.customSqlSegment}")
List getAll(@Param(Constants.WRAPPER) Wrapper wrapper);
6.分页的利用
@Data
public class UserVo extends BasePageRequest{
@ApiModelProperty(name = "user", value = "成员",dataType = "User",notes = "成员")
private User user;
}
//组装分页查询对象queryWrapper
public class UserserviceImpl extends ServiceImpl
implements userService {
@Autowired
private UserMapper userMapper;
public IPage getUserPage(UserVo userVo){
Page page = new Page(userVo.getPageNo(),userVo.getLimit());
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq(User.IS_DELETED, Constant.IS_DELETE_FALSE);
IPage userList = userMapper.selectPage(page, queryWrapper);
return userList;
}