一、SpringBoot整合MyBatis
1.导入依赖
尤其注意mysql依赖的版本,如果不设置可能由于你自己mysql安装版本太低而无法适应springboot默认配置的高版本,会使得数据库连接失败:
<!-- 对mybatis的支持 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.24</version>
<scope>runtime</scope>
</dependency>
2.yaml配置
配置完要检查属性是否配置成功,否则后序出问题很难发现:
datasource:
url: localhost:3306/movies
spring:
#关闭thymeleaf的缓存
thymeleaf:
cache: false
# 整合mybatis
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://${datasource.url}?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false&maxReconnects =10
username: root
password: root
hikari:
maximum-pool-size: 10 # 最大连接池数
max-lifetime: 1770000
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml #xml配置路径
# 设定别名
type-aliases-package: com.example.po
configuration:
map-underscore-to-camel-case: true #驼峰法命名
3.xxmapper.java 和xxmapper.xml文件的配置
xxmapper.java配置:
public interface FilmInfoMapper {
public FilminfoPO findById(Integer id);
public int updateById(int id);
}
xxmapper.xml配置
namespace(命名空间)的作用:
1)隔离sql语句,同一个命名空间的sql彼此可见,不同的命名空间彼此不可见,也就是说同一命名空间不能有相同id的sql语句,不同命名空间可以有;
2)通过命名空间可以找到与之对应的xxmapper接口;
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.FilmInfoMapper">
<!-- public FilminfoPO findById(Integer id);-->
<select id="findById" resultType="com.example.po.FilminfoPO" parameterType="Integer">
select *from tb_filminfo where filmid=#{id}
</select>
<!-- public int updateById(int id);-->
<update id="updateById">
update tb_filminfo set ticketprice=20 where filmid=#{id}
</update>
</mapper>
4.启动类加扫描mapper接口的注解
如果不加@MapperScan注解,那么每个mapper接口都得加@Mapper注解否则Spring Boot 找不到 Mapper:
@SpringBootApplication
@MapperScan("com.example.mapper")
public class DemoApplication {
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
class FilmInfoTest {
@Autowired
FilmInfoMapper mapper;
@Test
public void findByIdTest() {
Integer i=1;
System.out.println("FilmInfoPO:"+mapper.findById(i));
}
二、SpringBoot整合数据库事务管理
1.导入依赖
springboot的事务管理需要导入spring-boot-starter-jdbc;而我们导入的mybatis-spring-boot-starter包含了它,所以无需重复导入:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2.事务测试
1)mapper接口
@Insert("insert into tb_filminfo (typeid,filmname,ticketprice) values(#{typeid},#{filmname},#{ticketprice})")
int insert(FilminfoPO po);
2)service接口
public interface IFilmInfoService {
//插入一条记录
public int insert(FilminfoPO po);
3)service实现类
@Service
public class FilmInfoServiceImpl implements IFilmInfoService {
@Resource
private FilmInfoMapper mapper;
@Transactional
@Override
public int insert(FilminfoPO po) {
return mapper.insert(po);
}
4)controller类
@Controller
@RequestMapping("/film")
public class FilmInfoController {
@Resource
IFilmInfoService service;
@RequestMapping("/insert")
public String insert(FilminfoPO po) {
if (po!=null) {
int i = service.insert(po);
return "success";
} else {
return "false";
}
}
}
当没有异常抛出时添加成功,有异常出现添加失败。
三、Spring Boot中使用拦截器
1.自定义拦截类实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
String methodName = method.getName();
logger.info("方法{}被拦截", methodName);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.info("方法被执行,但是视图还未渲染");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.info("方法执行完毕,进行资源清理");
}
}
2.实现WebMvcConfigurer接口进行拦截配置
实现WebMvcConfigurer的这种配置会自动过滤静态资源:
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
测试结果:
10:52:16.316 [http-nio-8080-exec-1] INFO c.e.h.interceptors.MyInterceptor - 方法test被拦截
10:52:16.344 [http-nio-8080-exec-1] INFO c.e.h.interceptors.MyInterceptor - 方法被执行,但是视图还未渲染
10:52:16.344 [http-nio-8080-exec-1] INFO c.e.h.interceptors.MyInterceptor - 方法执行完毕,进行资源清理
需要整合的东西很多,明天继续!
|