本文主要是介绍快速上手高效插件:TKMybatis和MybatisPlus、Lomback,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.TKMybatis
1.依赖
<!--mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--springboot整合mybatis --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId></dependency><!--springboot整合tkmybatis --><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId></dependency><!--分页助手 --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId></dependency>
2.配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/(数据库名字)?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTCspring.datasource.username =xxxspring.datasource.password =xxxspring.datasource.driver-class-name=com.mysql.jdbc.Drivermybatis.type-aliases-package=(pojo的完整包名)#会把执行的sql语句输出在屏幕上mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3.创建实体类
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;//必须注解声明是哪个表
@Table(name = "brand")
public class Brand {//声明是主键@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
4.创建一个mapper包
5.在启动类注解@MapperScan
//注意是tkmybatis包下的
import tk.mybatis.spring.annotation.MapperScan@MapperScan(basePackages = "com.yzx.mapper")
5.创建实体类的mapper接口
- 如果有多表联查或者特殊需求要自己定义方法
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import tk.mybatis.mapper.common.Mapper;import java.util.List;public interface BrandMapper extends Mapper<Brand> {//自己添加的方法(一般多表联查都要自己定义方法与写sql语句)@Insert("INSERT INTO category_brand(category_id, brand_id) VALUES (#{cid},#{bid})")void insertBrandAndCategory(@Param("cid")long cid,@Param("bid")long bid);//自己添加的方法(一般多表联查都要自己定义方法与写sql语句)@Select("SELECT * FROM brand a INNER JOIN category_brand b on a.id=b.brand_id where b.category_id=#{cid3}")List<Brand> queryBrandsByCid3(@Param("cid3")long cid3);
}
6.在service的类 注入对应的mapper接口
//和Autowired效果一样 但是是通过名称注入 idea不显示红线@Resourceprivate BrandMapper brandMapper;
7.调用mapper的方法
- 简单方法
- 自定义条件
//通过example查询Example example=new Example(Brand.class);Example.Criteria criteria = example.createCriteria();//自定义查询条件criteria.andLike("name","%test%");//查询List<Brand> brandList = brandMapper.selectByExample(example);
8.分页助手
- 定义一个分页实体类
public class PageResult<T> {private Long total; //返回的个数private Integer totalPage; //总页数private List<T> items; //泛型:返回的数据PageResult(){}public PageResult(Long total, List<T> items) {this.total = total;this.items = items;}public PageResult(Long total, Integer totalPage, List<T> items) {this.total = total;this.totalPage = totalPage;this.items = items;}public Long getTotal() {return total;}public void setTotal(Long total) {this.total = total;}public Integer getTotalPage() {return totalPage;}public void setTotalPage(Integer totalPage) {this.totalPage = totalPage;}public List<T> getItems() {return items;}public void setItems(List<T> items) {this.items = items;} }
- 使用PageHelper分页
//page:页数(从1开始)、rows:查询个数PageHelper.startPage(page,rows);List<Brand> brandList = brandMapper.selectByExample(example);//取得分页结果PageInfo<Brand> pageInfo=new PageInfo<>(brandList);//通过PageInfo获得查询你结果个数与内容return new PageResult<Brand>(pageInfo.getTotal(),pageInfo.getList());
二.MybatisPlus
1.依赖
<!--mybatis-plus的springboot支持--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version></dependency><!--mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency>
2.配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/(数据库名字)?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTCspring.datasource.username =xxxspring.datasource.password =xxxspring.datasource.driver-class-name=com.mysql.jdbc.Driver#实体类别名mybatis-plus.typeAliasesPackage=(pojo的完整包名)#指定mapper.xml文件 mybatis-plus.mapper-locations =classpath:(src/main/resources下一层的放mapper.xml的文件夹名字)/*.xml
- 更多配置:http://mp.baomidou.com/guide/config.html#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
3.创建实体类
@TableName(value="表名")
public class User { @TableId(type = IdType.AUTO)private Long id; private String name; public Long getId() { return id; }public void setId(Long id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; }
}
4.创建mapper包
5.在启动类注解@MapperScan
import org.mybatis.spring.annotation.MapperScan;@MapperScan(" ")
6.创建实体类的mapper接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> { }
7.注入并使用
- 简单使用
@Autowired private UserMapper userMapper; @Test public void testSelect() { List<User> userList = userMapper.selectList(null); for (User user : userList) { System.out.println(user); } }
- 自定义查询
@Autowired private UserMapper userMapper; @Test public void testSelectByLike(){ //通过QueryWrapper构建查询条件QueryWrapper queryWrapper = new QueryWrapper(new User()); //查询名字中包含“o”的用户 queryWrapper.like("name", "o"); List<User> users = this.userMapper.selectList(queryWrapper); }
- 注意
- retBool:null != result && result >= 1 (即:修改 或 增加 的条数>=1 返回true)
- delBool:null != result && result >= 0 (即:删除 的条数>=0 返回true)
8.分页查询
- 给启动注入分页查询插件
@MapperScan("com.yzx.mybatisplus.mapper") @SpringBootApplication public class MyApplication { /*** 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
- 进行查询
@Test public void testSelectPage() { Page<User> page = new Page<>(1, 2); IPage<User> userIPage = this.userMapper.selectPage(page, null); System.out.println("总条数 ------> " + userIPage.getTotal()); System.out.println("当前页数 ------> " + userIPage.getCurrent()); System.out.println("当前每页显示数 ------> " + userIPage.getSize()); List<User> records = userIPage.getRecords(); for (User user : records) { System.out.println(user); } }
9.逆向工程
- 依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.5</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.0.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
- 代码
public class Generator {public static void main(String[] args) {AutoGenerator mpg = new AutoGenerator();// 选择 freemarker 引擎,默认 Velocitympg.setTemplateEngine(new FreemarkerTemplateEngine());/*** 全局配置*/GlobalConfig gc = new GlobalConfig();gc.setAuthor("yzx");gc.setOutputDir("C:\\EXCS\\IDEA_exc\\accout-mange\\src\\main\\java");gc.setFileOverride(false);// 是否覆盖同名文件,默认是false// 是否让每个实体类都继承Model 不需要ActiveRecord特性的请改为falsegc.setActiveRecord(false);gc.setEnableCache(false);// XML 二级缓存gc.setBaseResultMap(true);// XML ResultMapgc.setBaseColumnList(true);// XML columListgc.setOpen(false); //是否每次打开文件夹//配置Service接口的名称 %s会自动填充gc.setServiceName("%sService");mpg.setGlobalConfig(gc);/*** 数据源配置*/DataSourceConfig dsc = new DataSourceConfig();dsc.setDbType(DbType.MYSQL);dsc.setDriverName("com.mysql.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("Yang2000620");dsc.setUrl("jdbc:mysql://localhost:3306/account-mange?useUnicode=true&serverTimezone=UTC&characterEncoding=utf8");mpg.setDataSource(dsc);/*** 策略配置*/StrategyConfig strategy = new StrategyConfig();//strategy.setTablePrefix(new String[] { "buy_" });// 此处可以修改为您的表前缀strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略// 需要生成的表 不设置则生成所有表//strategy.setInclude(new String[] { "staff","role"});strategy.setEntityLombokModel(true); // 是否为lombok模型strategy.setEntityBooleanColumnRemoveIsPrefix(true); // Boolean类型字段是否移除is前缀mpg.setStrategy(strategy);/*** 包配置*/PackageConfig pc = new PackageConfig();pc.setParent("com.hfut.laboratory");pc.setEntity("pojo");mpg.setPackageInfo(pc);/*** 自定义配置(把mapper.xml生成到resources目录下)*/InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 velocity//String templatePath = "/templates/mapper.xml.vm";// 如果模板引擎是 freemarkerString templatePath = "/templates/mapper.xml.ftl";// 自定义输出配置(把mapper.xml生成到resources目录下)List<FileOutConfig> focList = new ArrayList<>();// 自定义配置会被优先输出focList.add(new FileOutConfig(templatePath) {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输出文件名return "C:\\EXCS\\IDEA_exc\\accout-mange\\src\\main\\resources\\mappers\\"+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);/*** 关闭默认 xml 生成*/mpg.setTemplate(// 关闭默认 xml 生成,调整生成 至 根目录new TemplateConfig().setXml(null));// 执行生成mpg.execute();}}
三.Lomback
1.依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> <version>1.18.4</version>
</dependency>
2.常用注解
- @Data:注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
- @Setter:注解在属性上;为属性提供 setting 方法
- @Getter:注解在属性上;为属性提供 getting 方法
- @Slf4j:注解在类上;为类提供一个 属性名为log 的 slf4j日志对象
- @NoArgsConstructor:注解在类上;为类提供一个无参的构造方法
- @AllArgsConstructor:注解在类上;为类提供一个全参的构造方法
- @Builder:使用Builder模式构建对
这里说一下@Builder 和 @Slf4j 怎么用 其他的相对好理解就不说了
-
@Bulider
@Builder public class User{private Long id;private String name; }
User user=User.builder().build();User user1=User.builder().id(1L).build();User user2=User.builder().id(2L).name("user").build();
-
@Slef4j:
- 加了这个注解可以直接使用 log 对象
@Slef4j pulic class UserService{public void func(){log.debug("debug");log.info("info");log.warn("warn");log.error("error");} }
这篇关于快速上手高效插件:TKMybatis和MybatisPlus、Lomback的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!