六、异常处理
通用异常 web和ajax
package com.example.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 处理错误页面 */ @ControllerAdvice public class CustomExceptionHandler { public static final String ERROR_VIEW = "thymeleaf/error"; @ExceptionHandler(value = Exception.class) public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception { if (isAjax(request)) { ModelAndView model = new ModelAndView(new MappingJackson2JsonView()); model.addObject("data", null); model.addObject("code", -1); model.addObject("msg", e.getMessage()); return model; } else { ModelAndView model = new ModelAndView(); model.addObject("exception", e); model.addObject("url", request.getRequestURL()); model.setViewName(ERROR_VIEW); return model; } } /** * 判断是否为ajax * * @param request * @return */ public boolean isAjax(HttpServletRequest request) { String ContentType = request.getHeader("Content-Type"); String Accept = request.getHeader("Accept"); if (ContentType != null && ContentType.contains("json")) { return true; } else if (Accept != null && Accept.contains("json")) { return true; } else { return false; } } }
处理ajax错误
package com.example.demo.exception; import com.example.demo.pojo.JsonResult; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 处理ajax错误 */ @RestControllerAdvice public class AjaxExceptionHandler { @ExceptionHandler(value = Exception.class) public JsonResult errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception { return JsonResult.error(e.getMessage()); } }
七、MyBatis
依赖引入pom.xml
<!--数据库相关--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <!--mapper--> <!--版本过低会报错--> <!--tk.mybatis.mapper.MapperException: tk.mybatis.mapper.provider.EmptyProvider中缺少selectOne方法!--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <!--pagehelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> <scope>compile</scope> <optional>true</optional> </dependency>
参数配置 application.properties
############################################################ # # druid # ############################################################ spring.datasource.url=jdbc:mysql://localhost:3306/data spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.druid.initial-size=1 spring.datasource.druid.min-idle=1 spring.datasource.druid.max-active=20 spring.datasource.druid.test-on-borrow=true #spring.datasource.druid.stat-view-servlet.allow=true ############################################################ # # mybatis # https://github.com/abel533/MyBatis-Spring-Boot ############################################################ mybatis.type-aliases-package=com.example.demo.pojo mybatis.mapper-locations=classpath:mapper/*.xml mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl # 通用mapper mapper.mappers=com.example.demo.utils.MyMapper mapper.not-empty=false mapper.identity=MYSQL # 分页插件 pagehelper.helperDialect=mysql pagehelper.reasonable=true pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql
自动代码生成配置 generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <property name="mappers" value="com.example.demo.utils.MyMapper"/> </plugin> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/data" userId="root" password="123456"> </jdbcConnection> <!-- 对于生成的pojo所在包 --> <javaModelGenerator targetPackage="com.example.demo.pojo" targetProject="src/main/java"/> <!-- 对于生成的mapper所在目录 --> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <!-- 配置mapper对应的java映射 --> <javaClientGenerator targetPackage="com.example.demo.mapper" targetProject="src/main/java" type="XMLMAPPER"/> <table tableName="sys_user"></table> </context> </generatorConfiguration>
逆向工程工具
package com.example.demo.utils; import java.io.File; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; public class GeneratorDisplay { public void generator() throws Exception{ List<String> warnings = new ArrayList<String>(); 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); } public static void main(String[] args) throws Exception { try { GeneratorDisplay generatorSqlmap = new GeneratorDisplay(); generatorSqlmap.generator(); } catch (Exception e) { e.printStackTrace(); } } }
通用Mapper
package com.example.demo.utils; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; /** * 继承自己的MyMapper */ public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> { //TODO //FIXME 特别注意,该接口不能被扫描到,否则会出错 } package com.example.demo.mapper; import com.example.demo.pojo.SysUser; import com.example.demo.utils.MyMapper; public interface UserMapper extends MyMapper<SysUser> { }
自定义Mapper
package com.example.demo.mapper; import com.example.demo.pojo.Person; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; // 自定义Mapper public interface PersonMapper { Person queryUserById(Integer id); @Transactional(propagation= Propagation.REQUIRED) void deleteById(Integer id); @Transactional(propagation= Propagation.REQUIRED) void updateById(Person person); }
mybatis
generatorConfig生成mapper和pojo
实现CURD
mybatis-pagehelper实现分页
自定义mapper实现
xml形式的sql形式有利于后期调优
使用包含pagehelper分页的MyBatis的开源框架:
https://github.com/abel533/MyBatis-Spring-Boot
事务:
事务隔离级别
default
read_uncommitted
read_committed
repeatable_read
serializable
事务传播行为
required 有事务直接用,没有新建事务
supports 有事务直接用,没有也可以
mandatory
requires_new
not_supported
never
nested
使用场景
@Transactional(propagation=Propagation.SUPPORTS)查询
@Transactional(propagation=Propagation.REQUIRED)增加,删除,修改
解决devtools与Mapper冲突
添加配置文件 META-INF/spring-devtools.properties
restart.include.hifi=/hifi-[\\w-\\.\\d]+.jar
restart.include.mybatis=/mybatis-[\\w-\\.\\d]+.jar
restart.include.mapper=/mapper-[\\w-\\.\\d]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.\\d]+jar