1.创建项目

1.创建项目

创建spring initializar项目,引入spring web模块

2.在pom.xml文件中引入依赖

引入spring boot、热部署、MySQL、mybatis、log4j

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.2.5.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.huang</groupId>
  12. <artifactId>parking-lot-server</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>parking-lot-server</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  18. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  19. <java.version>1.8</java.version>
  20. </properties>
  21. <dependencies>
  22. <!--spring boot-->
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <!--热部署-->
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-devtools</artifactId>
  31. <optional>true</optional>
  32. </dependency>
  33. <!--test-->
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-test</artifactId>
  37. <scope>test</scope>
  38. <exclusions>
  39. <exclusion>
  40. <groupId>org.junit.vintage</groupId>
  41. <artifactId>junit-vintage-engine</artifactId>
  42. </exclusion>
  43. </exclusions>
  44. </dependency>
  45. <!--mysql-->
  46. <dependency>
  47. <groupId>mysql</groupId>
  48. <artifactId>mysql-connector-java</artifactId>
  49. </dependency>
  50. <!--mybatisPlus-->
  51. <dependency>
  52. <groupId>com.baomidou</groupId>
  53. <artifactId>mybatis-plus-boot-starter</artifactId>
  54. <version>3.5.1</version>
  55. </dependency>
  56. <!--druid 数据库连接池-->
  57. <dependency>
  58. <groupId>com.alibaba</groupId>
  59. <artifactId>druid</artifactId>
  60. <version>1.1.16</version>
  61. </dependency>
  62. </dependencies>
  63. <build>
  64. <plugins>
  65. <plugin>
  66. <groupId>org.springframework.boot</groupId>
  67. <artifactId>spring-boot-maven-plugin</artifactId>
  68. </plugin>
  69. </plugins>
  70. </build>
  71. </project>

3.application.yml配置方式

3.1 静态指定,就是运行项目前指定使用的环境

  1. server:
  2. port: 9988
  3. spring:
  4. profiles:
  5. active: dev
  6. ---
  7. server:
  8. port: 9981
  9. spring:
  10. profiles: prod

注意每个环境之间使用—-分隔(注意是三个—-分隔),默认第一个是主环境。可以在默认环境指定使用其他环境。

3.2 动态切换

通过运行参数指定环境

  • Idea : 在application主运行类鼠标右键 -》 Edit 项目名application -》Program arguments -》输入 —spring.profiles.active=环境名,如下图

image.png

  • 通过maven的打jar包形式把项目打包,然后cmd运行,输入 java -jar 项目名.jar spring.profiles.active=环境名

通过vm参数指定环境
vm参数也在上图中,就是上图的VM options ,然后输入:-Dspring.profiles.active=环境名,注意开头是-D。

4..在application-dev.yml下添加配置

  1. spring:
  2. datasource:
  3. driver-class-name: com.mysql.cj.jdbc.Driver
  4. url: "jdbc:mysql://127.0.0.1:3306/parkingLot?serverTimezone=UTC"
  5. username: "root"
  6. password: "root"

2.配置MybatisPlus

1.添加依赖

  1. <!--mybatisPlus-->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-boot-starter</artifactId>
  5. <version>3.5.1</version>
  6. </dependency>

2.在application-dev.yml下添加配置

  1. mybatis-plus:
  2. # 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
  3. # 如果是放在resource目录 classpath:/mapper/*Mapper.xml
  4. mapper-locations: classpath:mybatis/mappers/*Mapper.xml
  5. #实体扫描,多个package用逗号或者分号分隔
  6. typeAliasesPackage: cn.saytime.model
  7. global-config:
  8. #主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
  9. id-type: 0
  10. #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
  11. field-strategy: 1
  12. #驼峰下划线转换
  13. #db-column-underline: true
  14. #刷新mapper 调试神器
  15. #refresh-mapper: true
  16. #数据库大写下划线转换
  17. #capital-mode: true
  18. # Sequence序列接口实现类配置
  19. #key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
  20. #逻辑删除配置(下面3个配置)
  21. #logic-delete-value: 1
  22. #logic-not-delete-value: 0
  23. #sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
  24. #自定义填充策略接口实现
  25. #meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
  26. configuration:
  27. map-underscore-to-camel-case: true
  28. cache-enabled: false
  29. #配置JdbcTypeForNull
  30. jdbc-type-for-null: 'null'

3.配置Druid数据源

1.添加依赖

  1. <!--druid 数据库连接池-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid</artifactId>
  5. <version>1.1.16</version>
  6. </dependency>

2.在application-dev.yml下添加配置

  1. spring:
  2. datasource:
  3. driver-class-name: com.mysql.cj.jdbc.Driver
  4. url: "jdbc:mysql://127.0.0.1:3306/parkingLot?serverTimezone=UTC"
  5. username: "root"
  6. password: "root"
  7. #指定数据源,不用默认的数据源
  8. type: com.alibaba.druid.pool.DruidDataSource
  9. # 数据源其他配置
  10. initialSize: 5
  11. minIdle: 5
  12. maxActive: 20
  13. maxWait: 60000
  14. timeBetweenEvictionRunsMillis: 60000
  15. minEvictableIdleTimeMillis: 300000
  16. validationQuery: SELECT 1 FROM DUAL
  17. testWhileIdle: true
  18. testOnBorrow: false
  19. testOnReturn: false
  20. poolPreparedStatements: true
  21. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  22. filters: stat,wall,log4j
  23. maxPoolPreparedStatementPerConnectionSize: 20
  24. useGlobalDataSourceStat: true
  25. connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

多数据源配置

  1. spring:
  2. datasource:
  3. master:
  4. jdbc-url: jdbc:mysql://192.168.102.31:3306/test
  5. username: root
  6. password: 123456
  7. driver-class-name: com.mysql.jdbc.Driver
  8. slave1:
  9. jdbc-url: jdbc:mysql://192.168.102.56:3306/test
  10. username: pig # 只读账户
  11. password: 123456
  12. driver-class-name: com.mysql.jdbc.Driver
  13. slave2:
  14. jdbc-url: jdbc:mysql://192.168.102.36:3306/test
  15. username: pig # 只读账户
  16. password: 123456
  17. driver-class-name: com.mysql.jdbc.Driver

3.配置Druid配置文件

  1. package com.example.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.alibaba.druid.support.http.StatViewServlet;
  4. import com.alibaba.druid.support.http.WebStatFilter;
  5. import org.springframework.boot.context.properties.ConfigurationProperties;
  6. import org.springframework.boot.web.servl
  7. et.FilterRegistrationBean;
  8. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import javax.sql.DataSource;
  12. import java.util.Arrays;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. @Configuration
  16. public class DruidConfig {
  17. @ConfigurationProperties(prefix = "spring.datasource")
  18. @Bean
  19. public DataSource druid(){
  20. return new DruidDataSource();
  21. }
  22. /**
  23. * 配置Druid的监控
  24. * 1.配置一个管理后台的Servlet
  25. * @return
  26. */
  27. @Bean
  28. public ServletRegistrationBean statViewServlet(){
  29. ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
  30. Map<String,String> initParams = new HashMap<>();
  31. initParams.put("loginUsername","admin");
  32. initParams.put("loginPassword","123456");
  33. //默认就是允许所有访问
  34. initParams.put("allow","");
  35. initParams.put("deny","192.168.15.21");
  36. bean.setInitParameters(initParams);
  37. return bean;
  38. }
  39. /**
  40. * 2、配置一个web监控的filter
  41. * @return
  42. */
  43. @Bean
  44. public FilterRegistrationBean webStatFilter(){
  45. FilterRegistrationBean bean = new FilterRegistrationBean();
  46. bean.setFilter(new WebStatFilter());
  47. Map<String,String> initParams = new HashMap<>();
  48. initParams.put("exclusions","*.js,*.css,/druid/*");
  49. bean.setInitParameters(initParams);
  50. bean.setUrlPatterns(Arrays.asList("/*"));
  51. return bean;
  52. }
  53. }

多数据源配置

  1. import com.alibaba.druid.pool.DruidDataSource;
  2. import org.apache.ibatis.session.SqlSessionFactory;
  3. import org.mybatis.spring.SqlSessionFactoryBean;
  4. import org.mybatis.spring.annotation.MapperScan;
  5. import org.springframework.beans.factory.annotation.Qualifier;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.boot.context.properties.ConfigurationProperties;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.context.annotation.Primary;
  11. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  12. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  13. import javax.sql.DataSource;
  14. @Configuration
  15. // 扫描 Mapper 接口并容器管理
  16. @MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
  17. public class MasterDataSourceConfig {
  18. // 精确到 master 目录,以便跟其他数据源隔离
  19. static final String PACKAGE = "org.spring.springboot.dao.master";
  20. static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";
  21. @Value("${master.datasource.url}")
  22. private String url;
  23. @Value("${master.datasource.username}")
  24. private String user;
  25. @Value("${master.datasource.password}")
  26. private String password;
  27. @Value("${master.datasource.driverClassName}")
  28. private String driverClass;
  29. @Bean(name = "masterDataSource")
  30. @Primary
  31. public DataSource masterDataSource() {
  32. DruidDataSource dataSource = new DruidDataSource();
  33. dataSource.setDriverClassName(driverClass);
  34. dataSource.setUrl(url);
  35. dataSource.setUsername(user);
  36. dataSource.setPassword(password);
  37. return dataSource;
  38. }
  39. @Bean(name = "masterTransactionManager")
  40. @Primary
  41. public DataSourceTransactionManager masterTransactionManager() {
  42. return new DataSourceTransactionManager(masterDataSource());
  43. }
  44. @Bean(name = "masterSqlSessionFactory")
  45. @Primary
  46. public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
  47. throws Exception {
  48. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  49. sessionFactory.setDataSource(masterDataSource);
  50. sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
  51. .getResources(MasterDataSourceConfig.MAPPER_LOCATION));
  52. return sessionFactory.getObject();
  53. }
  54. }
  1. import com.alibaba.druid.pool.DruidDataSource;
  2. import org.apache.ibatis.session.SqlSessionFactory;
  3. import org.mybatis.spring.SqlSessionFactoryBean;
  4. import org.mybatis.spring.annotation.MapperScan;
  5. import org.springframework.beans.factory.annotation.Qualifier;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.context.annotation.Primary;
  10. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  11. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  12. import javax.sql.DataSource;
  13. @Configuration
  14. // 扫描 Mapper 接口并容器管理
  15. @MapperScan(basePackages = ClusterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "clusterSqlSessionFactory")
  16. public class ClusterDataSourceConfig {
  17. // 精确到 cluster 目录,以便跟其他数据源隔离
  18. static final String PACKAGE = "org.spring.springboot.dao.cluster";
  19. static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml";
  20. @Value("${cluster.datasource.url}")
  21. private String url;
  22. @Value("${cluster.datasource.username}")
  23. private String user;
  24. @Value("${cluster.datasource.password}")
  25. private String password;
  26. @Value("${cluster.datasource.driverClassName}")
  27. private String driverClass;
  28. @Bean(name = "clusterDataSource")
  29. public DataSource clusterDataSource() {
  30. DruidDataSource dataSource = new DruidDataSource();
  31. dataSource.setDriverClassName(driverClass);
  32. dataSource.setUrl(url);
  33. dataSource.setUsername(user);
  34. dataSource.setPassword(password);
  35. return dataSource;
  36. }
  37. @Bean(name = "clusterTransactionManager")
  38. public DataSourceTransactionManager clusterTransactionManager() {
  39. return new DataSourceTransactionManager(clusterDataSource());
  40. }
  41. @Bean(name = "clusterSqlSessionFactory")
  42. public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
  43. throws Exception {
  44. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  45. sessionFactory.setDataSource(clusterDataSource);
  46. sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
  47. .getResources(ClusterDataSourceConfig.MAPPER_LOCATION));
  48. return sessionFactory.getObject();
  49. }
  50. }

4.测试获得的数据源类型

  1. @SpringBootTest
  2. class SpringBoot06DataJdbcApplicationTests {
  3. @Autowired
  4. DataSource dataSource;
  5. @Test
  6. void contextLoads() throws SQLException {
  7. System.out.println("获取的数据源===="+dataSource.getClass());
  8. Connection connection = dataSource.getConnection();
  9. System.out.println("获取的连接==="+connection);
  10. connection.close();
  11. }
  12. }

5.登录

可登录localhost:9988/druid/login.html

可能遇到的问题

在启动时报错

  1. ***************************
  2. APPLICATION FAILED TO START
  3. ***************************
  4. Description:
  5. Failed to bind properties under 'spring.datasource' to javax.sql.DataSource:
  6. Property: spring.datasource.filters
  7. Value: stat,wall,log4j
  8. Origin: class path resource [application.yml]:24:14
  9. Reason: org.apache.log4j.Logger
  10. Action:
  11. Update your application's configuration

根据报错提示在配置文件的24行,查看配置文件,该行代码是 filters: stat,wall,log4j
看报错原因Reason: org.apache.log4j.Logger,于是猜想少了log4j的相关依赖,在pom中引入相关依赖

  1. <!-- https://mvnrepository.com/artifact/log4j/log4j -->
  2. <dependency>
  3. <groupId>log4j</groupId>
  4. <artifactId>log4j</artifactId>
  5. <version>1.2.17</version>
  6. </dependency>

4.构建三层架构

如下图构建
image.png

1.实体类

entity类

  1. package com.huang.parkinglotserver.entity;
  2. import com.baomidou.mybatisplus.annotation.TableField;
  3. import com.baomidou.mybatisplus.annotation.TableId;
  4. import com.baomidou.mybatisplus.annotation.TableName;
  5. @TableName(value = "user")
  6. public class User {
  7. @TableId(value = "id")
  8. private String id;
  9. @TableField(value = "user_name")
  10. private String userName;
  11. @TableField(value = "user_password")
  12. private String userPassword;
  13. @TableField(value = "user_authority")
  14. private String userAuthority;
  15. //get、set方法
  16. }

前端传输数据,AO接收

  1. package com.huang.parkinglotserver.ao;
  2. public class UserAo {
  3. private String userName;
  4. private String userPassword;
  5. //get、set方法
  6. }

后端数据传送,VO传递

  1. package com.huang.parkinglotserver.vo;
  2. public class UserVo {
  3. private String userName;
  4. private String userPassword;
  5. private String userAuthority;
  6. //get、set方法
  7. }

2.controller层

  1. package com.huang.parkinglotserver.controller;
  2. import com.huang.parkinglotserver.ao.UserAo;
  3. import com.huang.parkinglotserver.service.UserService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.PostMapping;
  6. import org.springframework.web.bind.annotation.RequestBody;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @RestController
  10. @RequestMapping("/user")
  11. public class UserController {
  12. @Autowired
  13. private UserService userService;
  14. @PostMapping("/login")
  15. public boolean login(@RequestBody UserAo userAo) {
  16. userService.login(userAo);
  17. return true;
  18. }
  19. @POST
  20. @Path("/login")
  21. @Consumes({MediaType.TEXT_PLAIN})
  22. public Response test(@QueryParam("a") Integer a) {
  23. return Response.ok(true).build();
  24. }
  25. }

3.业务逻辑层

service层接口

  1. package com.huang.parkinglotserver.service;
  2. import com.baomidou.mybatisplus.extension.service.IService;
  3. import com.huang.parkinglotserver.ao.UserAo;
  4. import com.huang.parkinglotserver.entity.User;
  5. public interface UserService extends IService<User> {
  6. /**
  7. * 登录验证
  8. *
  9. * @param userAo 账号、密码
  10. * @return true成功、false失败
  11. */
  12. boolean login(UserAo userAo);
  13. }

service层接口实现类

  1. package com.huang.parkinglotserver.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.huang.parkinglotserver.ao.UserAo;
  4. import com.huang.parkinglotserver.dao.UserDao;
  5. import com.huang.parkinglotserver.entity.User;
  6. import com.huang.parkinglotserver.service.UserService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. @Service
  10. public class UserServiceImpl extends ServiceImpl<UserDao,User> implements UserService {
  11. @Autowired
  12. private UserDao userDao;
  13. @Override
  14. public boolean login(UserAo userAo) {
  15. User user = userDao.login(userAo.getUserName());
  16. if(user.getUserPassword().equals(userAo.getUserPassword())){
  17. return true;
  18. }else{
  19. return false;
  20. }
  21. }
  22. }

4.dao层

  1. package com.huang.parkinglotserver.dao;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.huang.parkinglotserver.entity.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.Select;
  6. @Mapper
  7. public interface UserDao extends BaseMapper<User> {
  8. /**
  9. * 登录验证
  10. * @param userName 账号
  11. * @return user账号密码信息
  12. */
  13. @Select("select * from user where user_name = '${value}'")
  14. User login(String userName);
  15. }

mybatisPlus的映射,一般在resource下的mapper

  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.huang.parkinglotserver.dao.UserDao">
  4. <select id="login" resultType="com.huang.parkinglotserver.entity.User">
  5. select u.id,u.user_name,u.user_password,u.user_authority
  6. from user u where user_name = "${value}"
  7. </select>
  8. </mapper>

XML形式实现多表查询

https://blog.csdn.net/weixin_42274148/article/details/121973513?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-8-121973513.pc_agg_new_rank&utm_term=mybatisplus+%E6%9F%A5%E8%AF%A2%E8%A1%A8%E4%B8%AD%E6%89%80%E6%9C%89%E6%95%B0%E6%8D%AE&spm=1000.2123.3001.4430
在PriClassMapper中添加方法

  1. public interface PriClassMapper extends BaseMapper<PriClass> {
  2. ClassDetail getDetailById(Serializable id);
  3. }

在XML文件中写SQL和映射

  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.example.primarySchool.mapper.PriClassMapper">
  4. <select id="getDetailById" resultMap="detailedClassResultMap">
  5. SELECT
  6. p.class_id AS class_id,
  7. p.nickname AS cname,
  8. s.student_id AS student_id,
  9. s.nickname AS sname
  10. FROM pri_class p JOIN student s
  11. ON p.class_id = s.class_id
  12. WHERE p.class_id = #{id}
  13. </select>
  14. <resultMap id="detailedClassResultMap" type="com.example.primarySchool.entity.ClassDetail">
  15. <result property="classId" column="class_id"/>
  16. <result property="nickname" column="cname"/>
  17. <collection property="students" ofType="com.example.primarySchool.entity.Student">
  18. <id property="studentId" column="student_id"/>
  19. <result property="nickname" column="sname"/>
  20. <result property="classId" column="class_id"/>
  21. </collection>
  22. </resultMap>
  23. </mapper>

再在service层中调用mapper中自定义的方法,通过getBaseMapper()来获取mapper的实例

  1. public interface IPriClassService extends IService<PriClass> {
  2. ClassDetail getDetailById(Serializable id);
  3. }
  1. @Service
  2. public class PriClassServiceImpl extends ServiceImpl<PriClassMapper, PriClass> implements IPriClassService {
  3. @Override
  4. public ClassDetail getDetailById(Serializable id) {
  5. return getBaseMapper().getDetailById(id);
  6. }
  7. }