1.依赖
mysql
mysql-connector-java
org.mybatis.spring.boot
mybatis-spring-boot-starter
tk.mybatis
mapper-spring-boot-starter
com.github.pagehelper
pagehelper-spring-boot-starter
2.配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/(数据库名字)?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username =xxx
spring.datasource.password =xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.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 {
//自己添加的方法(一般多表联查都要自己定义方法与写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 queryBrandsByCid3(@Param("cid3")long cid3);
}
6.在service的类 注入对应的mapper接口
//和Autowired效果一样 但是是通过名称注入 idea不显示红线
@Resource
private BrandMapper brandMapper;
7.调用mapper的方法
//通过example查询
Example example=new Example(Brand.class);
Example.Criteria criteria = example.createCriteria();
//自定义查询条件
criteria.andLike("name","%test%");
//查询
List brandList = brandMapper.selectByExample(example);
8.分页助手
public class PageResult {
private Long total; //返回的个数
private Integer totalPage; //总页数
private List items; //泛型:返回的数据
PageResult(){
}
public PageResult(Long total, List items) {
this.total = total;
this.items = items;
}
public PageResult(Long total, Integer totalPage, List 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 getItems() {
return items;
}
public void setItems(List items) {
this.items = items;
}
}
//page:页数(从1开始)、rows:查询个数
PageHelper.startPage(page,rows);
List brandList = brandMapper.selectByExample(example);
//取得分页结果
PageInfo pageInfo=new PageInfo<>(brandList);
//通过PageInfo获得查询你结果个数与内容
return new PageResult(pageInfo.getTotal(),pageInfo.getList());
1.依赖
com.baomidou
mybatis-plus-boot-starter
3.0.5
mysql
mysql-connector-java
5.1.47
2.配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/(数据库名字)?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username =xxx
spring.datasource.password =xxx
spring.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
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 {
}
7.注入并使用
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
List 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 users = this.userMapper.selectList(queryWrapper);
}
8.分页查询
@MapperScan("cn.itcast.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 page = new Page<>(1, 2);
IPage userIPage = this.userMapper.selectPage(page, null);
System.out.println("总条数 ------> " + userIPage.getTotal());
System.out.println("当前页数 ------> " + userIPage.getCurrent());
System.out.println("当前每页显示数 ------> " + userIPage.getSize());
List records = userIPage.getRecords();
for (User user : records) {
System.out.println(user);
}
}
9.逆向工程
com.baomidou
mybatis-plus-boot-starter
3.0.5
com.baomidou
mybatis-plus-generator
3.0.5
org.springframework.boot
spring-boot-starter-freemarker
mysql
mysql-connector-java
org.projectlombok
lombok
public class Generator {
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Velocity
mpg.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特性的请改为false
gc.setActiveRecord(false);
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
gc.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() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 velocity
//String templatePath = "/templates/mapper.xml.vm";
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置(把mapper.xml生成到resources目录下)
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public 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();
}
}
1.依赖
org.projectlombok
lombok
true
1.18.4
2.常用注解
这里说一下@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:
@Slef4j
pulic class UserService{
public void func(){
log.debug("debug");
log.info("info");
log.warn("warn");
log.error("error");
}
}