摘要:代碼自動(dòng)生成底層服務(wù)有很多通用的,利用代碼生成最好不過了,這里作者將代碼生成放在中的,避免與正式代碼沖突。主要通過來實(shí)現(xiàn),項(xiàng)目中的模板文件可以自行定義。相互學(xué)習(xí),共同進(jìn)步
從零開始學(xué)習(xí)Spring Boot也有幾天時(shí)間了,項(xiàng)目已經(jīng)不允許我這么慢慢學(xué)習(xí)了,急需底層變現(xiàn)實(shí)現(xiàn)一套簡(jiǎn)單的Restful API用于業(yè)務(wù)支撐。
于是在GitHub上找到了一個(gè)不錯(cuò)的demo,直接看demo搭建自己的項(xiàng)目了,這里記錄下在搭建過程中學(xué)習(xí)到的和遇到的問題。
先說說這個(gè)項(xiàng)目吧,項(xiàng)目結(jié)構(gòu),配置等非常精簡(jiǎn),對(duì)于新手的我來說還是比較容易上手的,對(duì)于學(xué)習(xí)和開發(fā)很有幫助,給作者點(diǎn)贊。
在此基礎(chǔ)上做了點(diǎn)滿足自身需求的改動(dòng),同時(shí)加入了swagger,順利的搭建了一套服務(wù)。
代碼自動(dòng)生成底層服務(wù)有很多通用的CRUD,利用代碼生成最好不過了,這里作者將代碼生成放在test中的 CodeGenerator,避免與正式代碼沖突。
生成的代碼不細(xì)說了,大家可以慢慢理解,覺得有困難的可以直接拿過來用。
主要通過org.mybatis.generator來實(shí)現(xiàn),項(xiàng)目中的generator.template模板文件可以自行定義。
Mybatis及分頁插件配置首先引用分頁插件包:
com.github.pagehelper pagehelper 4.2.1
然后進(jìn)行相應(yīng)的配置:
@Bean public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setTypeAliasesPackage(MODEL_PACKAGE); //配置分頁插件,詳情請(qǐng)查閱官方文檔 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("pageSizeZero", "true");//分頁尺寸為0時(shí)查詢所有紀(jì)錄不再執(zhí)行分頁 properties.setProperty("reasonable", "true");//頁碼<=0 查詢第一頁,頁碼>=總頁數(shù)查詢最后一頁 properties.setProperty("supportMethodsArguments", "true");//支持通過 Mapper 接口參數(shù)來傳遞分頁參數(shù) pageHelper.setProperties(properties); //添加插件 factory.setPlugins(new Interceptor[]{pageHelper}); //添加XML目錄 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); return factory.getObject(); }通用Mapper配置
引用通用mapper,簡(jiǎn)單的增刪改查就不用再寫對(duì)應(yīng)的xml了,之后有新增字段只要修改對(duì)應(yīng)的model就可以了,還是非常方便的。
引用對(duì)應(yīng)的包:
tk.mybatis mapper 3.4.2
然后進(jìn)行相應(yīng)的配置:
@Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean"); mapperScannerConfigurer.setBasePackage(MAPPER_PACKAGE); //配置通用Mapper,詳情請(qǐng)查閱官方文檔 Properties properties = new Properties(); properties.setProperty("mappers", MAPPER_INTERFACE_REFERENCE); properties.setProperty("notEmpty", "false");//insert、update是否判斷字符串類型!="" 即 test="str != null"表達(dá)式內(nèi)是否追加 and str != "" properties.setProperty("IDENTITY", "MYSQL"); mapperScannerConfigurer.setProperties(properties); return mapperScannerConfigurer; }生成代碼的實(shí)現(xiàn)
在分頁組件,通用mapper都配置完之后,我們需要通過自動(dòng)生成,根據(jù)自定義模板生成我們所需要的Model、Mapper、MapperXML、Service、ServiceImpl、Controller對(duì)應(yīng)的基礎(chǔ)代碼。
首先是模板的定義,定義常用的變量,定制你的代碼,比如service模板,這樣只要替換對(duì)應(yīng)的變量就可以達(dá)到生成需要的代碼的目的。
package ${basePackage}.service; import ${basePackage}.model.${modelNameUpperCamel}; import ${basePackage}.common.Service; /** * Created by ${author} on ${date}. */ public interface ${modelNameUpperCamel}Service extends Service<${modelNameUpperCamel}> { }
然后需要編寫下基于通用MyBatis Mapper插件的Service接口的實(shí)現(xiàn),從而在生成模板中根據(jù)該規(guī)則打通mapper與service層。
public abstract class AbstractServiceimplements Service { @Autowired protected Mapper mapper; private Class modelClass; // 當(dāng)前泛型真實(shí)類型的Class public AbstractService() { ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); modelClass = (Class ) pt.getActualTypeArguments()[0]; } public void save(T model) { mapper.insertSelective(model); } public void save(List models) { mapper.insertList(models); } public void deleteById(Long id) { mapper.deleteByPrimaryKey(id); } public void deleteByIds(String ids) { mapper.deleteByIds(ids); } public void update(T model) { mapper.updateByPrimaryKeySelective(model); } public T findById(Long id) { return mapper.selectByPrimaryKey(id); } @Override public T findBy(String fieldName, Object value) throws TooManyResultsException { try { T model = modelClass.newInstance(); Field field = modelClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(model, value); return mapper.selectOne(model); } catch (ReflectiveOperationException e) { throw new ServiceException(e.getMessage(), e); } } public List findByIds(String ids) { return mapper.selectByIds(ids); } public List findByCondition(Condition condition) { return mapper.selectByCondition(condition); } public List findAll() { return mapper.selectAll(); } }
具體的詳細(xì)代碼可以看下demo。
統(tǒng)一響應(yīng)結(jié)果和異常處理在配置springMVC時(shí),通過繼承WebMvcConfigurerAdapter,重寫對(duì)應(yīng)的方法,實(shí)現(xiàn)我們一些定制化的需求。
使用FastJson阿里的fstjson轉(zhuǎn)化效率還是比較高的,我們統(tǒng)一替換:
@Override public void configureMessageConverters(List統(tǒng)一異常處理> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,//保留空的字段 SerializerFeature.WriteNullStringAsEmpty,//String null -> "" SerializerFeature.WriteNullNumberAsZero);//Number null -> 0 converter.setFastJsonConfig(config); converter.setDefaultCharset(Charset.forName("UTF-8")); converters.add(converter); }
統(tǒng)一異常捕獲,在業(yè)務(wù)失敗直接使用ServiceException("message")拋出,統(tǒng)一輸出{"code":400,"message":"這里是錯(cuò)誤消息"}
@Override public void configureHandlerExceptionResolvers(List統(tǒng)一攔截器exceptionResolvers) { exceptionResolvers.add((request, response, handler, e) -> { Result result = new Result(); if (e instanceof ServiceException) {//業(yè)務(wù)失敗的異常,如“賬號(hào)或密碼錯(cuò)誤” result.setCode(ResultCode.FAIL).setMessage(e.getMessage()); logger.info(e.getMessage()); } else if (e instanceof NoHandlerFoundException) { result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在"); } else if (e instanceof ServletException) { result.setCode(ResultCode.FAIL).setMessage(e.getMessage()); } else { result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 內(nèi)部錯(cuò)誤,請(qǐng)聯(lián)系管理員"); String message; if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; message = String.format("接口 [%s] 出現(xiàn)異常,方法:%s.%s,異常摘要:%s", request.getRequestURI(), handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod().getName(), e.getMessage()); } else { message = e.getMessage(); } logger.error(message, e); } responseResult(response, result); return new ModelAndView(); }); }
可以通過重寫addInterceptors方法來自定義攔截,比如說用戶登錄,token驗(yàn)證等。
@Override public void addInterceptors(InterceptorRegistry registry) { //具體實(shí)現(xiàn) }添加Swagger
之前的文章有具體介紹配置Swagger,這里只要在之前的基礎(chǔ)上在springMVC配置項(xiàng)下添加swagger資源即可:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); }
實(shí)現(xiàn)效果如下,基本單表的操作不需要你編寫代碼了:
項(xiàng)目的基本內(nèi)容介紹到這里,具體的還是需要大家自行去看想代碼,實(shí)際操作一下。
總結(jié)看代碼的學(xué)習(xí)效率還是比看書快的,多實(shí)踐,實(shí)踐完看原理,感覺這樣最好。
如果想獲取對(duì)應(yīng)的代碼,可以關(guān)注我的公眾號(hào):Bug生活2048,回復(fù)SpringBoot就可以啦。
相互學(xué)習(xí),共同進(jìn)步~
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/68976.html
摘要:前兩篇已經(jīng)構(gòu)建了標(biāo)準(zhǔn)工程實(shí)例,也整合了實(shí)現(xiàn)了簡(jiǎn)單數(shù)據(jù)庫訪問,本篇主要更深入的學(xué)習(xí)下,實(shí)現(xiàn)較為完整的數(shù)據(jù)庫的標(biāo)準(zhǔn)服務(wù)。到這里,最復(fù)雜的數(shù)據(jù)訪問基本就算編寫完了。 前兩篇已經(jīng)構(gòu)建了RESTful API標(biāo)準(zhǔn)工程實(shí)例,也整合了MyBatis實(shí)現(xiàn)了簡(jiǎn)單數(shù)據(jù)庫訪問,本篇主要更深入的學(xué)習(xí)下,實(shí)現(xiàn)較為完整的數(shù)據(jù)庫CRUD的標(biāo)準(zhǔn)服務(wù)。 首先看下要實(shí)現(xiàn)的效果吧,完成下面截圖部分的API,除了CRUD之外...
摘要:通用是為了解決使用中的基本操作,使用它可以很方便的進(jìn)行開發(fā),可以節(jié)省開發(fā)人員大量的時(shí)間。當(dāng)該參數(shù)設(shè)置為時(shí),時(shí)會(huì)查詢第一頁,超過總數(shù)時(shí),會(huì)查詢最后一頁。 SpringBoot 是為了簡(jiǎn)化 Spring 應(yīng)用的創(chuàng)建、運(yùn)行、調(diào)試、部署等一系列問題而誕生的產(chǎn)物,自動(dòng)裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個(gè) WEB 工...
摘要:讀取控制臺(tái)內(nèi)容請(qǐng)輸入請(qǐng)輸入正確的代碼生成器全局配置實(shí)體屬性注解數(shù)據(jù)源配置包配置這里有個(gè)模塊名的配置,可以注釋掉不用。 最近在研究mybatis,然后就去找簡(jiǎn)化mybatis開發(fā)的工具,發(fā)現(xiàn)就有通用Mapper和mybatis-plus兩個(gè)比較好的可是使用,可是經(jīng)過對(duì)比發(fā)現(xiàn)還是mybatis-plus比較好,個(gè)人覺得,勿噴。。。 集成還是非常簡(jiǎn)單的,然后就在研究怎么分頁,開始研究通用ma...
springboot整合MySQL數(shù)據(jù)庫(MyBatis + 分頁配置) 一、POM文件添加依賴 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.1 com.github.pagehelper pagehelper 4.1.0 mysql mysql-connec...
閱讀 2649·2021-09-28 09:36
閱讀 2273·2021-09-07 09:58
閱讀 1536·2019-08-26 13:53
閱讀 1313·2019-08-23 17:53
閱讀 3059·2019-08-23 15:34
閱讀 1882·2019-08-23 15:34
閱讀 2907·2019-08-23 12:04
閱讀 3754·2019-08-23 10:56