- 新建一个Spring Initializr项目
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.4</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>aoyi</groupId> <artifactId>sn</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sn</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.0</version> </dependency> <!--缺少此jar包,导致@Mapper注解无效--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> <exclusions> <exclusion> <artifactId>mybatis</artifactId> <groupId>org.mybatis</groupId> </exclusion> </exclusions> </dependency> <!--分页插件--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> <exclusions> <exclusion> <artifactId>mybatis-spring-boot-starter</artifactId> <groupId>org.mybatis.spring.boot</groupId> </exclusion> </exclusions> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <!--swagger ui--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.29</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10</version> </dependency> <!--rabbitmq 依赖客户端--> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.8.0</version> </dependency> <!--操作文件流的一个依赖--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> </dependencies> <build> <!--读取数据库配置--> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.yml</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.0</version> <!-- 插件的依赖 --> <dependencies> <!-- 逆向工程的核心依赖 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.2</version> </dependency> <!-- MySQL驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.8</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
- 修改配置文件
将resource文件夹下原有的application.properties文件删除,创建application.yml配置文件(备注:其实SpringBoot底层会把application.yml文件解析为application.properties),本文创建了两个yml文件(application.yml和application-dev.yml)
application.yml
spring: profiles: active: dev
application-dev.yml
server: port: 8080 spring: datasource: username: root password: 1234 url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.jdbc.Driver #解决循环依赖的问题 main: allow-circular-references: true mybatis: mapper-locations: classpath:mapping/*.xml type-aliases-package: org.aoyi.sn.entity pagehelper: helperDialect: mysql reasonable: true page-size-zero: true supportMethodsArguments: true params: count=countSql #showSql logging: level: com.example.demo.mapper: debug
在项目中配置多套环境的配置方法。
笔记:在Spring Boot中多环境配置文件名需要满足application-{profile}.yml的格式,其中{profile}对应你的环境标识,比如:
application-dev.yml:开发环境
application-test.yml:测试环境
application-prod.yml:生产环境
至于哪个具体的配置文件会被加载,需要在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值。
- 在resource文件下创建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> <!-- targetRuntime: 执行生成的逆向工程的版本 MyBatis3Simple: 生成基本的CRUD(清新简洁版) MyBatis3: 生成带条件的CRUD(奢华尊享版) --> <context id="DB2Tables" targetRuntime="MyBatis3Simple"> <!-- 数据库的连接信息 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://rm-bp1vc9osk3mo2o4h3lo.mysql.rds.aliyuncs.com:端口/数据库名称" userId=" " password=" "></jdbcConnection> <!-- javaBean的生成策略--> <javaModelGenerator targetPackage="org.aoyi.sn.entity" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- SQL映射文件的生成策略 xml生成 --> <sqlMapGenerator targetPackage="mapping" targetProject=".\src\main\resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- Mapper接口的生成策略 --> <javaClientGenerator type="XMLMAPPER" targetPackage="org.aoyi.sn.mapper" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 逆向分析的表 --> <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName --> <!-- domainObjectName属性指定生成出来的实体类的类名 --> <table tableName="aoyi_sn_order" domainObjectName="AoyiSnOrder" /> </context> </generatorConfiguration>
- 右键Run maven build
- 生成效果
- 基本方法都已经生成好了
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="10 seconds"> <contextName>logback</contextName> <property name="log.path" value="D:/project/helen/guli_log/edu" /> //输出路径 <!--控制台日志格式:彩色日志--> <!-- magenta:洋红 --> <!-- boldMagenta:粗红--> <!-- cyan:青色 --> <!-- white:白色 --> <!-- magenta:洋红 --> <property name="CONSOLE_LOG_PATTERN" value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)"/> <!--文件日志格式--> <property name="FILE_LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss} |%-5level |%thread |%file:%line |%logger |%msg%n" /> <!--编码--> <property name="ENCODING" value="UTF-8" /> <!--输出到控制台--> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <!--日志级别--> <level>DEBUG</level> </filter> <encoder> <!--日志格式--> <Pattern>${CONSOLE_LOG_PATTERN}</Pattern> <!--日志字符集--> <charset>${ENCODING}</charset> </encoder> </appender> <!--输出到文件--> <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!--日志过滤器:此日志文件只记录INFO级别的--> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!-- 正在记录的日志文件的路径及文件名 --> <file>${log.path}/log_info.log</file> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>${ENCODING}</charset> </encoder> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 每天日志归档路径以及格式 --> <fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日志文件保留天数--> <maxHistory>15</maxHistory> </rollingPolicy> </appender> <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 日志过滤器:此日志文件只记录WARN级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>WARN</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!-- 正在记录的日志文件的路径及文件名 --> <file>${log.path}/log_warn.log</file> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>${ENCODING}</charset> <!-- 此处设置字符集 --> </encoder> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日志文件保留天数--> <maxHistory>15</maxHistory> </rollingPolicy> </appender> <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 日志过滤器:此日志文件只记录ERROR级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!-- 正在记录的日志文件的路径及文件名 --> <file>${log.path}/log_error.log</file> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>${ENCODING}</charset> <!-- 此处设置字符集 --> </encoder> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日志文件保留天数--> <maxHistory>15</maxHistory> </rollingPolicy> </appender> <!--开发环境--> <springProfile name="dev"> <!--可以灵活设置此处,从而控制日志的输出--> <root level="DEBUG"> <appender-ref ref="CONSOLE" /> <appender-ref ref="INFO_FILE" /> <appender-ref ref="WARN_FILE" /> <appender-ref ref="ERROR_FILE" /> </root> </springProfile> <!--生产环境--> <springProfile name="pro"> <root level="ERROR"> <appender-ref ref="ERROR_FILE" /> </root> </springProfile> </configuration>
创建util包 封装返回值
package aoyi.sn.util; /** * * @author LEOH * */ public class BaseResult<T> { private String retMsg; private String retCode; private T data; public T getData() { return data; } public void setData(T data) { this.data = data; } public String getRetMsg() { return retMsg; } public void setRetMsg(String retMsg) { this.retMsg = retMsg; } public String getRetCode() { return retCode; } public void setRetCode(String retCode) { this.retCode = retCode; } public BaseResult<T> buildOk(T t, String retMsg) { BaseResult<T> tBaseResult = new BaseResult<>(); tBaseResult.data = t; tBaseResult.retCode = Constants.SuccessCode; tBaseResult.retMsg = retMsg; return tBaseResult; } public BaseResult<T> buildFail(String retMsg){ BaseResult<T> tBaseResult = new BaseResult<>(); tBaseResult.retCode = Constants.FailCode; tBaseResult.retMsg = retMsg; return tBaseResult; } }
package aoyi.sn.util; public class Constants { public static final String Query = "[查询]"; public static final String Add = "[新增]"; public static final String Update = "[更新]"; public static final String Delete = "[删除]"; public static final String Duplicate = "[重复]"; public static String SplitChar = "_"; /** * 24*3600*10 10 days */ public static final long ExpireTime = 864000; public static final String FailCode = "FAIL"; public static final String SuccessCode = "OKAY"; public static final int PageSize = 10; }
select标签常用属性
parameterType 传入参数 支持map javaBean等值 resultMap 返回参数
Mapper增加
public List<AoyiSnCategory> selectAll(Map<String, Object> paras);
xml增加
<sql id="Base_Column_List"> id, create_by, create_time, update_by, update_time, sn_category_id, sn_category_name, sn_category_level, sn_category_parent_id </sql>
<select id="selectAll" resultMap="BaseResultMap" > select <include refid="Base_Column_List" /> from aoyi_sn_category </select>
创建service
@Service public interface AoyiSnCategoryService { public BaseResult<PageInfo<AoyiSnCategory>> getSnCategorys(Map<String, Object> paras); }
创建serviceimpl
import java.util.*; @Service @Transactional(rollbackFor = { RuntimeException.class, Exception.class }) public class AoyiSnCategoryServiceImpl implements AoyiSnCategoryService { private static final Logger logger = LoggerFactory.getLogger(AoyiSnCategoryService.class); @Autowired private AoyiSnCategoryMapper aoyiSnCategoryMapper; @Override public BaseResult<PageInfo<AoyiSnCategory>> getSnCategorys(Map<String, Object> paras) { logger.info("查询类型列表"); BaseResult<PageInfo<AoyiSnCategory>> baseRet = new BaseResult<PageInfo<AoyiSnCategory>>(); baseRet.setRetCode(Constants.FailCode); baseRet.setRetMsg(Constants.Query); int pageNo = Integer.parseInt(String.valueOf(paras.get("pageNo"))); int pageSize = Integer.parseInt(String.valueOf(paras.get("pageSize"))); PageHelper.startPage(pageNo, pageSize); List<AoyiSnCategory> list = aoyiSnCategoryMapper.selectAll(paras); PageInfo<AoyiSnCategory> pageDataList = new PageInfo<AoyiSnCategory>(list); baseRet.setData(pageDataList); baseRet.setRetCode(Constants.SuccessCode); return baseRet; } }
controller
@RestController @RequestMapping("/AoyiSnCategory") public class AoyiSnCategoryController { @Autowired private AoyiSnCategoryService aoyiSnCategoryService; //查询 @RequestMapping(value = "getAoyiSnCategorys", method = RequestMethod.POST) @ResponseBody public BaseResult<PageInfo<AoyiSnCategory>> getDeviceTypeByParas(@RequestBody Map<String, Object> paras){ return aoyiSnCategoryService.getSnCategorys(paras); } }
启动
测试查询 封装好了分页 查询2条
配置了日志 打印sql 需下载mybatis Log 插件
增加
public Integer insertAoyiSnCategory(Map<String, Object> paras);
@Override public BaseResult<Integer> insertAoyiSnCategory(Map<String, Object> paras) { BaseResult<Integer> baseRet = new BaseResult<Integer>(); baseRet.setRetCode(Constants.FailCode); baseRet.setRetMsg(Constants.Add); String createTime = DateUtil.formatYYYYMMDDHHMMSS(new Date()); paras.put("createTime", createTime); paras.put("id", UUID.randomUUID().toString()); Integer integerBaseResult = aoyiSnCategoryMapper.insertAoyiSnCategory(paras); baseRet.setData(integerBaseResult); baseRet.setRetCode(Constants.SuccessCode); return baseRet; }
<insert id="insertAoyiSnCategory" parameterType="java.util.Map"> insert into aoyi_sn_category (id, create_by, create_time, update_by, update_time, sn_category_id, sn_category_name, sn_category_level, sn_category_parent_id ) values (#{id,jdbcType=VARCHAR}, #{createBy,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateBy,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}, #{snCategoryId,jdbcType=VARCHAR}, #{snCategoryName,jdbcType=VARCHAR}, #{snCategoryLevel,jdbcType=VARCHAR}, #{snCategoryParentId,jdbcType=VARCHAR} ) </insert>
//增加 @RequestMapping(value = "/insertAoyiSnCategorys", method = RequestMethod.POST) @ResponseBody public BaseResult<Integer> insertAoyiSnCategorys(@RequestBody Map<String, Object> paras){ return aoyiSnCategoryService.insertAoyiSnCategory(paras); }
测试
修改
public int updateAoyiSnCategory(Map<String, Object> paras);
<update id="updateAoyiSnCategory" parameterType="java.util.Map"> update aoyi_sn_category <set> <if test="snCategoryName != null and snCategoryName != ''">sn_category_name = #{snCategoryName}</if> </set> WHERE id = #{id} </update>
@Override public BaseResult<Integer> updateAoyiSnCategory(Map<String, Object> paras) { BaseResult<Integer> baseRet = new BaseResult<Integer>(); baseRet.setRetCode(Constants.FailCode); baseRet.setRetMsg(Constants.Update); int ret = aoyiSnCategoryMapper.updateAoyiSnCategory(paras); baseRet.setData(ret); baseRet.setRetCode(Constants.SuccessCode); return baseRet; }
@RequestMapping(value = "/updateAoyiSnCategory", method = RequestMethod.POST) @ResponseBody public BaseResult<Integer> updateAoyiSnCategory(@RequestBody Map<String, Object> paras){ return aoyiSnCategoryService.updateAoyiSnCategory(paras); }
测试
删除
public BaseResult<Integer> deleteDeviceType(int id);
@Override public BaseResult<Integer> delectAoyiSnCategory(String id) { BaseResult<Integer> baseRet = new BaseResult<Integer>(); baseRet.setRetCode(Constants.FailCode); baseRet.setRetMsg(Constants.Delete); int ret = aoyiSnCategoryMapper.deleteByPrimaryKey(id); baseRet.setData(ret); baseRet.setRetCode(Constants.SuccessCode); return baseRet; }
@RequestMapping(value = "/delectAoyiSnCategory", method = RequestMethod.POST) @ResponseBody public BaseResult<Integer> delectAoyiSnCategory(@RequestBody Map<String, Object> paras){ return aoyiSnCategoryService.delectAoyiSnCategory((String) paras.get("id")); }
idea上传项目到gitee(码云)超详细
(3条消息) idea上传项目到gitee(码云)超详细_『愚』的博客-CSDN博客_idea上传项目到gitee
剩下内容以后在加入
package org.aoyi.sn.mqtt; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class RabbitMqUtils { //得到一个连接的 channel public static Channel getChannel() throws Exception{ //创建一个连接工厂 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.1.125"); factory.setUsername("admin"); factory.setPassword("123"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); return channel; } }