创建SpringBoot项目
开始配置
一、pom文件配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.17</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.0</version> </dependency> <!--freemarker模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
项目结构
application.yml 主要配置文件
#默认使用配置环境 spring: profiles: active: dev
application-dev.yml 开发环境
#开发环境 server: port: 8082 #datasource spring: mvc: static-path-pattern: /static/** view: prefix: /templates/ suffix: .ftl datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: timeBetweenEvictionRunsMillis: 60000 minEvictionRunsMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 # Redis数据库索引(默认为0) redis: database: 0 timeout: 0 # Redis服务器地址 host: 127.0.0.1 # Redis服务器连接端口 port: 6379 # 连接池最大连接数(使用负值表示没有限制) pool: max-active: 8 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1 # 连接池中的最大空闲连接 max-idle: 8 # 连接池中的最小空闲连接 min-idle: 0 cluster: max-redirects: 10 nodes: 127.0.0.1:6080 #mybatis mybatis: mapper-locations: classpath:mapping/*Mapper.xml type-aliases-package: com.example.demo.entity configuration: map-underscore-to-camel-case: true #showSql logging: level: com.example.demo.dao: debug
application-prod.yml 生成环境
application-test.yml 测试环境
程序启动类
@SpringBootApplication @MapperScan("com.example.demo.dao") //扫描的mapper public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
看到这个说明启动成功
通过mybatis访问数据库
@Autowired private UserService userService; @RequestMapping public String job() { return "index"; } @ApiOperation(value = "获取用户信息", notes = "根据url的id来获取详细信息") @ApiImplicitParams({ @ApiImplicitParam(paramType = "path", name = "id", dataType = "int", required = true, value = "用户id", defaultValue = ""), }) @GetMapping("/user/{id}") public User getUser(@PathVariable Integer id, @PathVariable String name) { if (id == null) { return null; } return userService.getUser(id); }
service
@Resource private UserMapper userMapper; @Autowired private RedisJson redisJson; /** * 获取redis的数据 * * @param id * @return */ public User getUser(Integer id) { User user = redisJson.get("user", User.class); if (user == null) { user = findById(id); } return user; } /** * 查询数据库 * @param id * @return */ public User findById(Integer id) { User user = userMapper.findById(id); redisJson.set("user", user); return user; }
dao
public interface UserMapper { User findById(Integer id); }
mapper.xml
<?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.uwang.hellospringboot.dao.UserMapper"> <select id="findById" resultType="user"> select * from user where id=#{id} </select> </mapper>
generatorConfig代码生成器配置
<?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> <!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 --> <classPathEntry location="C:\application\lib\mysql-connector-java-5.1.47.jar"/> <context id="Tables" targetRuntime="MyBatis3"> <!-- 注释 --> <commentGenerator> <!-- 是否生成注释代时间戳 --> <property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- JDBC连接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useSSL=false&nullNamePatternMatchesAll=true" userId="root" password="123456"> </jdbcConnection> <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制--> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成实体类地址 --> <javaModelGenerator targetPackage="com.example.demo.entity" targetProject="src/main/java"> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true"/> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false"/> </javaModelGenerator> <!-- 生成mapper xml文件 --> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 生成mapper xml对应Client--> <javaClientGenerator targetPackage="com.example.demo.dao" targetProject="src/main/java" type="XMLMAPPER"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 配置表信息 --> <!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample 是否生成 example类 --> <table tableName="t_course" domainObjectName="Course" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> </context> </generatorConfiguration>
运行即可生成代码