spring+springmvc+mybatis-plus 纯注解开发
最近刚完成一个项目,刚好有一点时间,来完成基于spring+springmvc+mybatis-plus 纯注解开发
一、创建工程、导入依赖
1、新建一个基于maven的web工程,使用JDK1.8
2、调整目录结构
2.1、新建java
2.2、新建resources
2.3、删除web.xml、构建基础包
2.4、工程目录构建完成展示
2、配置tomcat服务器
2.1、服务器配置
2.2、测试服务器配置
3、pom.xml文件配置
1 <properties> 2 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 3 <maven.compiler.source>1.8</maven.compiler.source> 4 <maven.compiler.target>1.8</maven.compiler.target> 5</properties> 6 7<dependencies> 8 <dependency> 9<groupId>org.springframework</groupId> 10<artifactId>spring-context</artifactId> 11<version>5.1.5.RELEASE</version> 12 </dependency> 13 <dependency> 14<groupId>org.springframework</groupId> 15<artifactId>spring-core</artifactId> 16<version>5.1.5.RELEASE</version> 17 </dependency> 18 <dependency> 19<groupId>org.springframework</groupId> 20<artifactId>spring-beans</artifactId> 21<version>5.1.5.RELEASE</version> 22 </dependency> 23 <dependency> 24<groupId>org.springframework</groupId> 25<artifactId>spring-web</artifactId> 26<version>5.1.5.RELEASE</version> 27 </dependency> 28 <dependency> 29<groupId>org.springframework</groupId> 30<artifactId>spring-webmvc</artifactId> 31<version>5.1.5.RELEASE</version> 32 </dependency> 33 <dependency> 34<groupId>org.springframework</groupId> 35<artifactId>spring-aop</artifactId> 36<version>5.1.5.RELEASE</version> 37 </dependency> 38 <dependency> 39<groupId>org.springframework</groupId> 40<artifactId>spring-tx</artifactId> 41<version>5.1.5.RELEASE</version> 42 </dependency> 43 <dependency> 44<groupId>org.springframework</groupId> 45<artifactId>spring-jdbc</artifactId> 46<version>5.1.5.RELEASE</version> 47 </dependency> 48 <dependency> 49<groupId>org.mybatis</groupId> 50<artifactId>mybatis-spring</artifactId> 51<version>1.3.2</version> 52 </dependency> 53 <dependency> 54<groupId>org.mybatis</groupId> 55<artifactId>mybatis</artifactId> 56<version>3.4.6</version> 57 </dependency> 58 <dependency> 59<groupId>com.baomidou</groupId> 60<artifactId>mybatis-plus</artifactId> 61<version>3.0.7.1</version> 62 </dependency> 63 <dependency> 64<groupId>com.baomidou</groupId> 65<artifactId>mybatis-plus-generator</artifactId> 66<version>3.0.7.1</version> 67 </dependency> 68 <dependency> 69<groupId>org.apache.velocity</groupId> 70<artifactId>velocity-engine-core</artifactId> 71<version>2.0</version> 72 </dependency> 73 <dependency> 74<groupId>org.apache.commons</groupId> 75<artifactId>commons-lang3</artifactId> 76<version>3.7</version> 77 </dependency> 78 <dependency> 79<groupId>com.fasterxml.jackson.core</groupId> 80<artifactId>jackson-core</artifactId> 81<version>2.9.8</version> 82 </dependency> 83 <dependency> 84<groupId>com.fasterxml.jackson.core</groupId> 85<artifactId>jackson-databind</artifactId> 86<version>2.9.8</version> 87 </dependency> 88 <dependency> 89<groupId>com.fasterxml.jackson.core</groupId> 90<artifactId>jackson-annotations</artifactId> 91<version>2.9.8</version> 92 </dependency> 93 <dependency> 94<groupId>com.oracle</groupId> 95<artifactId>ojdbc6</artifactId> 96<version>11.2.0.1.0</version> 97 </dependency> 98 <dependency> 99<groupId>mysql</groupId>100<artifactId>mysql-connector-java</artifactId>101<version>6.0.5</version>102 </dependency>103 <dependency>104<groupId>com.mchange</groupId>105<artifactId>c3p0</artifactId>106<version>0.9.5.2</version>107 </dependency>108 <dependency>109<groupId>com.mchange</groupId>110<artifactId>c3p0</artifactId>111<version>0.9.5.2</version>112 </dependency>113 <dependency>114<groupId>com.alibaba</groupId>115<artifactId>druid</artifactId>116<version>1.1.10</version>117 </dependency>118 <dependency>119<groupId>org.projectlombok</groupId>120<artifactId>lombok</artifactId>121<version>1.18.8</version>122<scope>provided</scope>123 </dependency>124 <dependency>125<groupId>junit</groupId>126<artifactId>junit</artifactId>127<version>4.11</version>128<scope>test</scope>129 </dependency>130 <dependency>131<groupId>javax.servlet</groupId>132<artifactId>javax.servlet-api</artifactId>133<version>3.1.0</version>134<scope>provided</scope>135 </dependency>136</dependencies>137 138<build>139 <finalName>loginannotationday02</finalName>140 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->141<plugins>142 <plugin>143<artifactId>maven-clean-plugin</artifactId>144<version>3.1.0</version>145 </plugin>146 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->147 <plugin>148<artifactId>maven-resources-plugin</artifactId>149<version>3.0.2</version>150 </plugin>151 <plugin>152<artifactId>maven-compiler-plugin</artifactId>153<version>3.8.0</version>154 </plugin>155 <plugin>156<artifactId>maven-surefire-plugin</artifactId>157<version>2.22.1</version>158 </plugin>159 <plugin>160<artifactId>maven-war-plugin</artifactId>161<version>3.2.2</version>162 </plugin>163 <plugin>164<artifactId>maven-install-plugin</artifactId>165<version>2.5.2</version>166 </plugin>167 <plugin>168<artifactId>maven-deploy-plugin</artifactId>169<version>2.8.2</version>170 </plugin>171</plugins>172 </pluginManagement>173</build>
二、编写mybatis-plus的代码生成工具
调整目录结构
在util下新建mybatis代码生成工具类
mybatisplusutil代码如下
1 package com.cxw.util; 2 3 import com.baomidou.mybatisplus.annotation.DbType; 4 import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; 5 import com.baomidou.mybatisplus.core.toolkit.StringPool; 6 import com.baomidou.mybatisplus.generator.AutoGenerator; 7 import com.baomidou.mybatisplus.generator.InjectionConfig; 8 import com.baomidou.mybatisplus.generator.config.*; 9 import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert; 10 import com.baomidou.mybatisplus.generator.config.po.TableInfo; 11 import com.baomidou.mybatisplus.generator.config.rules.IColumnType; 12 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; 13 import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine; 14 import org.apache.commons.lang3.StringUtils; 15 16 import java.util.ArrayList; 17 import java.util.List; 18 import java.util.Scanner; 19 20 public class MybatisPlusUtil{ 21 22 /** 23 * <p> 24 * 读取控制台内容 25 * </p> 26 */ 27 static String Scanner(String tip) { 28 Scanner scanner = new Scanner(System.in); 29 StringBuilder help = new StringBuilder(); 30 help.append("请输入" + tip + ":"); 31 System.out.println(help.toString()); 32 if (scanner.hasNext()) { 33 String ipt = scanner.next(); 34 if (StringUtils.isNotEmpty(ipt)) { 35 retu ipt; 36 } 37 } 38 throw new MybatisPlusException("请输入正确的" + tip + "!"); 39 } 40 41 public static void main(String[] args) { 42 //代码生成器 43 AutoGenerator autoGenerator = new AutoGenerator(); 44 45 //全局配置 46 GlobalConfig globalConfig = new GlobalConfig(); 47 final String projectPath = System.getProperty("user.dir"); 48 globalConfig.setOutputDir(projectPath + "/src/main/java"); 49 globalConfig.setAuthor("cxw"); 50 //globalConfig.setOpen(false); 51 //是否覆盖文件 52 globalConfig.setFileOverride(true); 53 //不需要ActiveRecord特性的请改为false 54 globalConfig.setActiveRecord(false); 55 //XML 二级缓存 56 globalConfig.setEnableCache(false); 57 //XML ResultMap 58 globalConfig.setBaseResultMap(true); 59 //XML columList 60 globalConfig.setBaseColumnList(false); 61 autoGenerator.setGlobalConfig(globalConfig); 62 63 //数据源配置 64 DataSourceConfig dataSourceConfig = new DataSourceConfig(); 65 dataSourceConfig.setDbType(DbType.MYSQL); 66 //类型转换 67 dataSourceConfig.setTypeConvert(new OracleTypeConvert(){ 68 @Override 69 public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) { 70 retu super.processTypeConvert(globalConfig, fieldType); 71 } 72 }); 73 dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/cxwdb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"); 74 dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver"); 75 dataSourceConfig.setUseame("root"); 76 dataSourceConfig.setPassword("123456"); 77 autoGenerator.setDataSource(dataSourceConfig); 78 79 80 81 //包配置 82 final PackageConfig packageConfig = new PackageConfig(); 83 //基础包名 84 packageConfig.setParent("com.cxw"); 85 //模块名 86 packageConfig.setModuleName(Scanner("模块名")); 87 packageConfig.setService("service"); 88 packageConfig.setServiceImpl("service.impl"); 89 packageConfig.setEntity("entity"); 90 packageConfig.setController("controller"); 91 packageConfig.setMapper("mapper"); 92 packageConfig.setXml("mapper"); 93 autoGenerator.setPackageInfo(packageConfig); 94 95 // 自定义配置 96 InjectionConfig injectionConfig = new InjectionConfig() { 97 @Override 98 public void initMap() { 99 // to do nothing100 }101 };102 List<FileOutConfig> focList = new ArrayList<>();103 focList.add(new FileOutConfig("/templates/mapper.xml.vm") {104 @Override105 public String outputFile(TableInfo tableInfo) {106 // 自定义输入文件名称107 retu projectPath + "/src/main/resources/mapper/" + packageConfig.getModuleName()108 + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;109 }110 });111 injectionConfig.setFileOutConfigList(focList);112 autoGenerator.setCfg(injectionConfig);113 autoGenerator.setTemplate(new TemplateConfig().setXml(null));114 115 // 策略配置116 StrategyConfig strategy = new StrategyConfig();117 strategy.setNaming(NamingStrategy.underline_to_camel);118 strategy.setColumnNaming(NamingStrategy.underline_to_camel);119 strategy.setEntityLombokModel(false);120 strategy.setRestControllerStyle(true);121 strategy.setCapitalMode(true);122 strategy.setInclude(Scanner("表名"));123 strategy.setControllerMappingHyphenStyle(true);124 strategy.setEntityTableFieldAnnotationEnable(true);125 //strategy.setTablePrefix("n_");126 autoGenerator.setStrategy(strategy);127 autoGenerator.setTemplateEngine(new VelocityTemplateEngine());128 autoGenerator.execute();129 }130 }
通过工具类生成代码
生成后目录结构如下
三、spring+springmvc+mybatis-plus 纯注解搭建
1、构建核心配置文件
1 package com.cxw.config; 2 3 import org.springframework.context.annotation.ComponentScan; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.context.annotation.FilterType; 6 import org.springframework.stereotype.Controller; 7 8 9 @Configuration10 @ComponentScan(basePackages = {"com.cxw"},excludeFilters = {11 @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class),12 })13 /**14 * 核心配置文件15 */16 public class AppConfig {17 18 }
2、构建springmvc配置文件
1 package com.cxw.config; 2 3 import org.springframework.context.annotation.ComponentScan; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.context.annotation.FilterType; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 8 9 @Configuration10 @ComponentScan(basePackages = "com.cxw",11 includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,12 value = Controller.class)})13 @EnableWebMvc14 /**15 * springmvc配置文件16 */17 public class WebConfig {18 19 }
3、构建数据库配置文件
1 spring.datasource.user=root2 spring.datasource.password=1234563 spring.datasource.driver=com.mysql.cj.jdbc.Driver4 spring.datasource.url=jdbc:mysql://localhost:3306/cxwdb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
4、构建数据库配置文件关联文件
1 package com.cxw.config; 2 3 import lombok.Data; 4 import org.springframework.beans.factory.annotation.Value; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.context.annotation.PropertySource; 7 8 @PropertySource("classpath:db.properties") 9 @Data10 @Configuration11 public class PropertyConfig {12 13 @Value("${spring.datasource.url}")14 private String url;15 @Value("${spring.datasource.driver}")16 private String driver;17 @Value("${spring.datasource.user}")18 private String user;19 @Value("${spring.datasource.password}")20 private String password;21 22 }
5、构建mybatisplus配置文件
1 package com.cxw.config; 2 3 import com.alibaba.druid.pool.DruidDataSource; 4 import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; 5 import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; 6 import org.mybatis.spring.annotation.MapperScan; 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.Configuration; 9 10 import javax.sql.DataSource;11 12 @Configuration13 @MapperScan(value = "com.cxw.studentinfo.mapper")14 public class MybatisPlusConfig {15 /**16 * 配置数据源17 */18 @Bean19 public DataSource dataSource(PropertyConfig propertyConfig){20 DruidDataSource dataSource = new DruidDataSource();21 dataSource.setUseame(propertyConfig.getUser());22 dataSource.setPassword(propertyConfig.getPassword());23 dataSource.setUrl(propertyConfig.getUrl());24 dataSource.setDriverClassName(propertyConfig.getDriver());25 retu dataSource;26 }27 28 /*@Bean29 public DataSource dataSource(PropertyConfig propertyConfig) throws Exception {30 ComboPooledDataSource dataSource = new ComboPooledDataSource();31 dataSource.setUser(propertyConfig.getUser());32 dataSource.setPassword(propertyConfig.getPassword());33 dataSource.setJdbcUrl(propertyConfig.getUrl());34 dataSource.setDriverClass(propertyConfig.getDriver());35 retu dataSource;36 }*/37 38 /**39 * 获得getMybatisSqlSessionFactoryBean40 * @retu41 */42 @Bean43 public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){44 MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();45 mybatisPlus.setDataSource(dataSource);46 retu mybatisPlus;47 }48 49 50 /**51 * 设置mapper文件的扫描路径52 * @retu53 */54/* @Bean55 public MapperScannerConfigurer getMapperScannerConfigurer(){56 MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();57 mapperScannerConfigurer.setBasePackage("com.cxw.studentinfo,mapper");58 retu mapperScannerConfigurer;59 }*/60 61 /**62 * 分页插件63 * @retu64 */65 @Bean66 public PaginationInterceptor getPaginationInterceptor(){67 PaginationInterceptor paginationInterceptor = new PaginationInterceptor();68 //自定义方言 可以没有69 paginationInterceptor.setDialectType("mysql");70 retu paginationInterceptor;71 }72 73 }
6、构建核心初始化文件
package com.cxw.config;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;/** * web.xml替代文件,可以简单理解为相web.xml文件 */public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {//将bean加入容器@Overrideprotected Class<?>[] getRootConfigClasses() {//这里可以配置需要加入容器的Bean,同样可以声明配置类,然后加Beanretu new Class[]{AppConfig.class,MybatisPlusConfig.class};}//这个也是相当于将Bean加入容器//相当于springmvc容器// url映射配置,返回spring的配置文件//这里WebConfig主要是配置DispatcherSerlvet,视频解析器,JSON等@Overrideprotected Class<?>[] getServletConfigClasses() {//retu null;retu new Class[]{WebConfig.class};}//拦截请求匹配,只拦截/@Overrideprotected String[] getServletMappings() {retu new String[]{"/"};}}
四、逻辑代码编写
1、controller代码
package com.cxw.studentinfo.controller;import com.cxw.studentinfo.entity.TblStudent;import com.cxw.studentinfo.service.ITblStudentService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * <p> * 前端控制器 * </p> * * @author cxw * @since 2019-09-25 */@RestController@RequestMapping("/studentinfo/tbl-student")public class TblStudentController {private ITblStudentService iTblStudentService;@Autowiredpublic TblStudentController(ITblStudentService iTblStudentService){this.iTblStudentService = iTblStudentService;}public TblStudentController(){}@RequestMapping("/gettblstudentbyid/{id}")public TblStudent getTblStudentById(@PathVariable("id") String id){TblStudent student = iTblStudentService.getById(id);retu student;}}
2、serivce代码
1 package com.cxw.studentinfo.service; 2 3 import com.cxw.studentinfo.entity.TblStudent; 4 import com.baomidou.mybatisplus.extension.service.IService; 5 6 /** 7 * <p> 8 * 服务类 9 * </p>10 *11 * @author cxw12 * @since 2019-09-2513 */14 public interface ITblStudentService extends IService<TblStudent> {15 16 }
3、impl代码
package com.cxw.studentinfo.service.impl;
import com.cxw.studentinfo.entity.TblStudent;
import com.cxw.studentinfo.mapper.TblStudentMapper;
import com.cxw.studentinfo.service.ITblStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author cxw
* @since 2019-09-25
*/
@Service
public class TblStudentServiceImpl extends ServiceImpl<TblStudentMapper, TblStudent> implements ITblStudentService {
private TblStudentMapper tblStudentMapper;
@Autowired
public TblStudentServiceImpl(TblStudentMapper tblStudentMapper){
this.tblStudentMapper = tblStudentMapper;
}
public TblStudentServiceImpl( ){
}
4、mapper代码
1 package com.cxw.studentinfo.mapper; 2 3 import com.cxw.studentinfo.entity.TblStudent; 4 import com.baomidou.mybatisplus.core.mapper.BaseMapper; 5 import org.springframework.stereotype.Service; 6 7 /** 8 * <p> 9 * Mapper 接口10 * </p>11 *12 * @author cxw13 * @since 2019-09-2514 */15 @Service16 public interface TblStudentMapper extends BaseMapper<TblStudent> {17 18 }
5、entity代码
1 package com.cxw.studentinfo.entity; 2 3 import com.baomidou.mybatisplus.annotation.TableId; 4 import java.time.LocalDateTime; 5 import com.baomidou.mybatisplus.annotation.TableField; 6 import java.io.Serializable; 7 8 /** 9 * <p> 10 * 11 * </p> 12 * 13 * @author cxw 14 * @since 2019-09-25 15 */ 16 public class TblStudent implements Serializable { 17 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * 主键 22 */ 23 @TableId("id") 24 private String id; 25 26 /** 27 * 姓名 28 */ 29 @TableField("name") 30 private String name; 31 32 /** 33 * 年龄 34 */ 35 @TableField("age") 36 private String age; 37 38 /** 39 * 性别 40 */ 41 @TableField("sex") 42 private String sex; 43 44 /** 45 * 数据新增用户id 46 */ 47 @TableField("datainsuserid") 48 private String datainsuserid; 49 50 /** 51 * 数据新增时间 52 */ 53 @TableField("datainstime") 54 private LocalDateTime datainstime; 55 56 57 public String getId() { 58 retu id; 59 } 60 61 public void setId(String id) { 62 this.id = id; 63 } 64 65 public String getName() { 66 retu name; 67 } 68 69 public void setName(String name) { 70 this.name = name; 71 } 72 73 public String getAge() { 74 retu age; 75 } 76 77 public void setAge(String age) { 78 this.age = age; 79 } 80 81 public String getSex() { 82 retu sex; 83 } 84 85 public void setSex(String sex) { 86 this.sex = sex; 87 } 88 89 public String getDatainsuserid() { 90 retu datainsuserid; 91 } 92 93 public void setDatainsuserid(String datainsuserid) { 94 this.datainsuserid = datainsuserid; 95 } 96 97 public LocalDateTime getDatainstime() { 98 retu datainstime; 99 }100 101 public void setDatainstime(LocalDateTime datainstime) {102 this.datainstime = datainstime;103 }104 105 @Override106 public String toString() {107 retu "TblStudent{" +108 "id=" + id +109 ", name=" + name +110 ", age=" + age +111 ", sex=" + sex +112 ", datainsuserid=" + datainsuserid +113 ", datainstime=" + datainstime +114 "}";115 }116 }
6、mapper.xml代码
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <mapper namespace="com.cxw.studentinfo.mapper.TblStudentMapper"> 4 5 <!-- 通用查询映射结果 --> 6 <resultMap id="BaseResultMap" type="com.cxw.studentinfo.entity.TblStudent"> 7 <id column="id" property="id" /> 8 <result column="name" property="name" /> 9 <result column="age" property="age" />10 <result column="sex" property="sex" />11 <result column="datainsuserid" property="datainsuserid" />12 <result column="datainstime" property="datainstime" />13 </resultMap>14 15 </mapper>
五、测试
1、数据库查询结果展示
2、运行程序,访问后结构展示
六、总结和疑问
1、使用代码生成器的时候,如果使用的是Oracle数据库,表名似乎需要大写才能生成
2、配置mapper扫包的时候,如果使用非注解的形式,似乎会造成重复扫包,导致会找不到service文件
以上两个问题是我在构建项目的时候遇到的问题
作者:saber-servlet
来源链接:https://www.cnblogs.com/saber-servlet/p/11586511.html
版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。
2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。