java 笔记 —— spring boot 项目开发

1 时间

1.1 获取当前时间
  • 获取 年、月;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
1.2 设置时间(精确至秒)
  • 获取本月第一天零点;
    • 如需上月最后一天,firstDay - 1 即可;
Calendar cal = Calendar.getInstance();
int firstDay = cal.getMinimum(Calendar.DATE);
cal.set(year, month, firstDay, 0, 0, 0);
Date firstDate = cal.getTime();
  • 获取本月最后一天 23 点 59 分 59 秒;
Calendar cal2 =Calendar.getInstance();
cal2.set(Calendar.YEAR, year);
cal2.set(Calendar.MONTH, month);
int lastDay = cal2.getActualMaximum(Calendar.DAY_OF_MONTH);
cal2.set(year, month, lastDay, 23, 59, 59);
Date lastDate = cal2.getTime();

2 cors 跨域配置

  • 新建一个 class 直接粘贴即可,重写了 spring 中的方法,配置了请求头;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOriginPatterns("*")
            .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
            .allowCredentials(true)
            .maxAge(3600)
            .allowedHeaders("*");
  }
}

3 mybatis-plus

3.1 基于 xml 的自定义 sql
  • 文件结构如下:
    在这里插入图片描述
第一步 创建 *Mapper.xml
  • 1 上图的 xml 创建在 resources 中,代码如下:
<?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.tang.bill.mapper.BillMapper">
    <select id="selectTestWithSqlInXml" resultType="map">
        SELECT single_bill.*, bill_type.nature FROM single_bill LEFT JOIN bill_type ON bill_type.uuid=single_bill.type ORDER BY single_bill.bill_date
    </select>
</mapper>
  • 2 namespace 中的文件地址是指向 Mapper 的接口类;
  • 3 如果 resultType 需要用实体类,也需要完整的路径,如 com.tang.bill.pojo.Bill;
第二步 接口类创建相应方法
  • 接口类路径:com.tang.bill.mapper.BillMapper
@Repository
public interface BillMapper extends BaseMapper<Bill> {
  List<Map> selectTestWithSqlInXml();
}
第三步 propertoes 中配置 xml 路径
  • resources 中配置 application.properties:
mybatis-plus.mapper-locations=classpath:/mapper/**.xml
第四步 pom 中避免对 *Mapper.xml 的编译
    <build>
        <resources>
            <resource>
                <directory>src/main/java/resources/mapper</directory>
                <includes>
                    <include>*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
第五步 使用
  @Test
  void selectTestWithSqlInXml() {
    List<Map> maps = billMapper.selectTestWithSqlInXml();
    for (Map map : maps) {
      System.out.println(map.toString());
    }
  }
3.2 在接口类中自定义 sql
public interface BillMapper extends BaseMapper<Bill> {
  // 自定义 sql 语句
  @Select("select single_bill.*, bill_type.nature from single_bill left join bill_type on bill_type.uuid=single_bill.type ${ew.customSqlSegment}")
  List<Map> selectBillWithWrapper(@Param(Constants.WRAPPER) Wrapper<Map> billWrapper);
}
  • 1 在这里面进行联表查询的字段不易出现重复,其问题会在 wrapper 使用中出现;
  • 2 当两表均有 name 字段时,下面的代码生成的 sql 语句为如下第二个代码块,很明显的是在此时该 sql 语句无法正常运行:
    QueryWrapper wrapper = new QueryWrapper();
    wrapper.between("bill_date", firstDate, lastDate);
    wrapper.like("creater", creater);
    wrapper.orderByAsc("name");
    List<Map> bills = billMapper.selectBillWithWrapper(wrapper);
select single_bill.*, bill_type.nature 
from single_bill 
left join bill_type on bill_type.uuid=single_bill.type 
order by name
  • 3 mybatis 中对于 sql 语句的标签存在多种应用,如某条件存在才生成对应的 sql 语句,这种功能在使用此方法时无法使用;
  • 4 wrapper 的使用相对简陋,无法实现联表等操作;

4 spring-boot + mybatis-plus 的多数据库(mysql)配置

在这里插入图片描述

4.1 application.properties 配置
spring.datasource.old.jdbc-url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.old.username=root
spring.datasource.old.password=password
spring.datasource.old.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.news.jdbc-url=jdbc:mysql://localhost:3306/mybatisplus?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.news.username=root
spring.datasource.news.password=password
spring.datasource.news.driver-class-name=com.mysql.jdbc.Driver


mybatis-plus.mapper-locations=classpath*:/mapper/**/*Mapper.xml
4.2 config 配置文件编写
4.2.1 DataSourceNewsConfig
package com.tang.multiplemysqlmybatisplus.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.mybatis.spring.SqlSessionTemplate;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.tang.multiplemysqlmybatisplus.pojo.news", sqlSessionTemplateRef = "newsSqlSessionTemplate")
public class DataSourceNewsConfig {

  @Bean(name = "newsDataSource")
  @ConfigurationProperties(prefix = "spring.datasource.news")
  public DataSource testDataSource() {
    System.out.println("init testnewsDataSource");
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "newsSqlSessionFactory")
  public SqlSessionFactory newsSqlSessionFactory(@Qualifier("newsDataSource") DataSource dataSource) throws Exception {
    //SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setTypeEnumsPackage("com.tang.multiplemysqlmybatisplus.enums");
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/news/*.xml"));
    return bean.getObject();
  }

  @Bean(name = "newsSqlSessionTemplate")
  public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("newsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}
4.2.2 DataSourceOldConfig
package com.tang.multiplemysqlmybatisplus.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.mybatis.spring.SqlSessionTemplate;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.tang.multiplemysqlmybatisplus.pojo.old", sqlSessionTemplateRef = "oldSqlSessionTemplate")
public class DataSourceOldConfig {

  @Bean(name = "oldDataSource")
  @Primary
  @ConfigurationProperties(prefix = "spring.datasource.old")
  public DataSource testDataSource() {
    System.out.println("init testDataSource");
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "oldSqlSessionFactory")
  public SqlSessionFactory oldSqlSessionFactory(@Qualifier("oldDataSource") DataSource dataSource) throws Exception {
    //SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setTypeEnumsPackage("com.tang.multiplemysqlmybatisplus.enums");
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/old/*.xml"));
    return bean.getObject();
  }

  @Bean(name = "oldSqlSessionTemplate")
  @Primary
  public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("oldSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}
4.2.3 MultipleMysqlMybatisplusApplication
  • MapperScan 装饰器添加
package com.tang.multiplemysqlmybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@MapperScan("com.tang.multiplemysqlmybatisplus.mapper")
public class MultipleMysqlMybatisplusApplication {

  public static void main(String[] args) {
    SpringApplication.run(MultipleMysqlMybatisplusApplication.class, args);
  }

}
4.3 其它
  • 其它配置与一般 mybatis-plus 相同;
  • 但是现在存在的问题是,现在将 news 对应的配置设为 @Primary,因此只有这个是可以通过使用 xml 的 sql 进行操作的;
    在这里插入图片描述

5 正则实现内容抽取

  // 按指定模式在字符串查找
  String line = "【asin】as";
  String pattern = "^(【)(.*)(】)(.*)$";

  // 创建 Pattern 对象
  Pattern r = Pattern.compile(pattern);

  // 现在创建 matcher 对象
  Matcher m = r.matcher(line);
  if (m.find( )) {
    // 全部原始文本
    System.out.println("Found value: " + m.group(0) );
    // 对应第一个括号内的正则公式
    System.out.println("Found value: " + m.group(1) );
    // 对应第二个括号内的正则公式
    System.out.println("Found value: " + m.group(2) );
    // 对应第三个括号内的正则公式
    System.out.println("Found value: " + m.group(3) );
    // 对应第四个括号内的正则公式
    System.out.println("Found value: " + m.group(4) );
  } else {
    System.out.println("NO MATCH");
  }

6 读取properties文件中的自定义字段

  @Test
  void testReadProperties() {
  	// application为属性文件名,放在src下的
    ResourceBundle resource = ResourceBundle.getBundle("application");
    String key = resource.getString("testA");
    System.out.println(key);
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值