项目结构示意图:
4.0.0
com.wang
springboot-mybatis
0.0.1-SNAPSHOT
jar
springboot-mybatis
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.5.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-configuration-processor
true
org.springframework.boot
spring-boot-maven-plugin
方法二: Mybatis逆向工程
案例演示:Mabatis逆向工程生成POJO和Mapper.xml文件
弹出窗口如下:
01.生成的dao层代码如下:
@Repository
public interface TbPersonDao {
int insert(TbPersonPO po);
int batchInsert(List list);
int update(TbPersonPO po);
int delete(TbPersonPO po);
List query(TbPersonQuery query);
long count(TbPersonQuery query);
}
02.生成model层代码如下:
生成com.wang.mybatis.model.po.TbPersonPO类
public class TbPersonPO {
private Integer id;
private String name;
private Integer age;
//省略getter和人setter方法
@Override
public String toString() {
return "TbPersonPO{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
生成com.wang.mybatis.model.query.TbPersonQuery类
public class TbPersonQuery {
private Integer id;
private String name;
private Integer age;
private Long offset;
private Integer limit;
//省略setter和getter方法
}
03.生成sql映射文件:mapper/tbPerson.xml
INSERT INTO tb_person(id,name,age)
VALUES(null,#{name},#{age})
INSERT INTO tb_person(id,name,age)
VALUES
(null,#{item.name},#{item.age})
ON DUPLICATE KEY UPDATE
id=VALUES(id),name=VALUES(name),age=VALUES(age)
UPDATE tb_person
name=#{name},
age=#{age},
WHERE id=#{id}
id,name,age
from tb_person
AND id=#{id}
AND name=#{name}
AND age=#{age}
delete from tb_person where id=#{id}
# 配置数据库连接的账号、密码、url、数据库驱动
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_person
# 使用mybatis操作数据库配置以下内容
mybatis:
#type-aliases-package: com.wang.mybatis.dao #可以添加此属性
mapper-locations: classpath:mapper/*xml # 指定配置mapper文件的位置
/*@MapperScan: 指定扫描的具体包
* */
@MapperScan(basePackages = {"com.wang.mybatis.dao"})
@SpringBootApplication
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
TbPersonDao tbPersonDao;
TbPersonPO tbPersonPO=new TbPersonPO();
TbPersonQuery tbPersonQuery=new TbPersonQuery();
/* 1. 添加数据*/
@Test
public void insert() {
tbPersonPO.setAge(23);
tbPersonPO.setName("曹操");
tbPersonDao.insert(tbPersonPO);
logger.info("数据添加成功!");
}
/* 2. 修改数据*/
@Test
public void update() {
tbPersonPO.setId(6); /* 指定具体要修改对象的id*/
tbPersonPO.setAge(22);
tbPersonPO.setName("刘华");
tbPersonDao.update(tbPersonPO);
logger.info("数据修改成功!");
}
/* 3.查询数据*/
@Test
public void query(){
/* 起始位置*/
tbPersonQuery.setOffset(1L);
/* 限制查询条数用于分页使用*/
tbPersonQuery.setLimit(3);
List list=tbPersonDao.query(tbPersonQuery);
for(TbPersonPO tbPersonPO:list){
System.out.println(tbPersonPO);
}
}
/* 4. 删除数据*/
@Test
public void delete(){
tbPersonPO.setId(8);
int data=tbPersonDao.delete(tbPersonPO);
if(data>0){
System.out.println("数据删除成功");
}
}
/* 4.统计数据*/
@Test
public void count(){
long count=tbPersonDao.count(tbPersonQuery);
System.out.println(count);
}
/* 5. 批量操作*/
@Test
public void batchInsert(){
List list=new ArrayList();
TbPersonPO tbPersonPO1=new TbPersonPO();
tbPersonPO1.setName("王杰");
tbPersonPO1.setAge(16);
list.add(tbPersonPO1);
TbPersonPO tbPersonPO2=new TbPersonPO();
tbPersonPO2.setName("张杰伦");
tbPersonPO2.setAge(36);
list.add(tbPersonPO2);
tbPersonDao.batchInsert(list);
}
}
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源,现在我们要把Druid作为数据源操作步骤如下:
com.alibaba
druid
1.1.8
log4j
log4j
1.2.17
# 配置数据库连接的账号、密码、url、数据库驱动
spring:
datasource:
# 数据源基本配置
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_person
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# 使用mybatis操作数据库配置以下内容
mybatis:
#type-aliases-package: com.wang.mybatis.dao #可以添加此属性
# 指定全局配置文件位置
#config-location: classpath:mapper/mybatis-config.xml
mapper-locations: classpath:mapper/*xml # 指定配置sql文件的位置
com.wang.mybatis.config.DruidConfig类的作用:给组件绑定数据、并把组件添加到容器中!
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map initParams = new HashMap<>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
initParams.put("allow", "");//默认就是允许所有访问
initParams.put("deny", "192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
DataSource dataSource;
/* 测试数据源的类型*/
@Test
public void dataSource() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection=dataSource.getConnection();
connection.close();
}
}
设置断点测试数据是否绑定
如图所示:
使用Druid monitor的具体步骤:
1.引入依赖
com.github.pagehelper
pagehelper
5.1.2
com.github.pagehelper
pagehelper-spring-boot-autoconfigure
1.2.3
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.3
2.配置PageHelper相关属性
方法一:在application.yml文件中配置
# 配置pagehelper参数
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
方法二:创建一个配置类配置 PageHelper
@Configuration
public class PageHelperConfig {
@Bean
public PageHelper getPageHelper(){
PageHelper pageHelper=new PageHelper();
Properties properties=new Properties();
properties.setProperty("helperDialect","mysql");
properties.setProperty("reasonable","true");
properties.setProperty("supportMethodsArguments","true");
properties.setProperty("params","count=countSql");
pageHelper.setProperties(properties);
return pageHelper;
}
}
3.PageInfo类源码的属性如下:
public class PageInfo implements Serializable {
private static final long serialVersionUID = 1L;
//当前页
private int pageNum;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//由于startRow和endRow不常用,这里说个具体的用法
//可以在页面中"显示startRow到endRow 共size条数据"
//当前页面第一个元素在数据库中的行号
private int startRow;
//当前页面最后一个元素在数据库中的行号
private int endRow;
//总记录数
private long total;
//总页数
private int pages;
//结果集
private List list;
//前一页
private int prePage;
//下一页
private int nextPage;
//是否为第一页
private boolean isFirstPage = false;
//是否为最后一页
private boolean isLastPage = false;
//是否有前一页
private boolean hasPreviousPage = false;
//是否有下一页
private boolean hasNextPage = false;
//导航页码数
private int navigatePages;
//所有导航页号
private int[] navigatepageNums;
//导航条上的第一页
private int navigateFirstPage;
//导航条上的最后一页
private int navigateLastPage;
}
4.前段请求接口方法
@RequestMapping(value = "/getPerson")
public List getSomePerson(@RequestParam(value = "pageNum",defaultValue="1") int pageNum ){
//pageNum:表示第几页 pageSize:表示一页展示的数据
PageHelper.startPage(pageNum,3);
List list=tbPersonDao.queryPerosn();
//将查询到的数据封装到PageInfo对象
PageInfo pageInfo=new PageInfo(list,3);
//分割数据成功
return list;
}
5.测试分页插件配置是否成功配置
使用Mybatis Generator简化开发、提升开发效率。Mybatis Generator为我们生产sql映射文件、JavaBean及dao接口。
Mybatis Generator最完整配置详解
通过运行Java代码的方式生成Bean、Dao、sql映射文件
public class GeneratorMain {
public static void main(String[] args) {
List warnings = new ArrayList();
boolean overwrite = true;
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}