window.cnblogsConfig = { blogUser: 'MoYu', blogAvatar: 'https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg', blogStartDate: '2020-02-09', webpageTitleOnblur: '(o゚v゚)ノ Hi,Back', webpageTitleOnblurTimeOut: 500, webpageTitleFocus: '(*´∇`*) 欢迎回来!', webpageTitleFocusTimeOut: 1000, webpageIcon: "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210213094450.jpg", enable: true, // 是否开启日/夜间模式切换按钮 auto: { // 自动切换相关配置 enable: false, // 开启自动切换 dayHour: 7, // 日间模式开始时间,整数型,24小时制 nightHour: 20 // 夜间模式开始时间,整数型,24小时制 } switchDayNight: { enable: true, auto: { enable: true } }, progressBar: { id : 'top-progress-bar', // 请勿修改该值 color : '#77b6ff', height : '2px', duration: 0.2, }, loading: { rebound: { tension: 16, friction: 5, }, spinner: { id: 'spinner', radius: 90, sides: 3, depth: 4, colors: { background: '#f0f0f0', stroke: '#272633', base: null, child: '#272633', }, alwaysForward: true, // When false the spring will reverse normally. restAt: 0.5, // A number from 0.1 to 0.9 || null for full rotation renderBase: false, } }, homeTopAnimationRendered: true, homeTopAnimation: { radius: 15, density: 0.2, color: 'rgba(255,255,255, .2)', // 颜色设置,“random” 为随机颜色 clearOffset: 0.3, }, essayTopAnimationRendered: true, essayTopAnimation: { triW : 14, triH : 20, neighbours : ["side", "top", "bottom"], speedTrailAppear : .1, speedTrailDisappear : .1, speedTriOpen : 1, trailMaxLength : 30, trailIntervalCreation : 100, delayBeforeDisappear : 2, colorsRandom: false, // v1.2.4 是否开启随机颜色 colors: [ '#96EDA6', '#5BC6A9', '#38668C', '#374D84', '#BED5CB', '#62ADC6', '#8EE5DE', '#304E7B' ] }, homeTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/home_top_bg.webp" ], homeBannerTextType: "one", essayTopImg: [ "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://cdn.jsdelivr.net/gh/BNDong/Cnblogs-Theme-SimpleMemory@master/img/webp/nothome_top_bg.webp", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190902.jpg", "https://gitee.com/MoYu-zc/picgo/raw/master/img/20210208190954.jpg", ], codeMaxHeight: true, codeLineNumber: true, essayCode: { fontFamily: "'Ubuntu Mono',monospace", // 代码框字体 fontSize: "14px" // 代码框字体大小 }, }

SpringBoot-07 整合

SpringBoot-07 整合

首先肯定是创建一个项目,前面的都一样,加入的依赖不太一样:

1

加入这两个,创建就可以。

整合JDBC

1.查看默认数据源

1.1 导入配置

创建一个application.yml,这里添加的数据库是我学习Mybatis使用的数据库,你们也可以自行创建。

spring:
  datasource:
    username: root
    password: 148729
    url: jdbc:mysql://localhost:3306/mybatistest?userUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

1.2 测试默认数据源

@SpringBootTest
class JdbcApplicationTests {

    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        // 默认数据源
        System.out.println(dataSource.getClass());
    }
}

结果为:com.zaxxer.hikari.HikariDataSource

1.3 数据库连接

@SpringBootTest
class JdbcApplicationTests {

    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

这时候可能遇到时区错误,可以在url中增加serverTimezone=UTC

 url: jdbc:mysql://localhost:3306/mybatistest?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8

2.jdbcTemplate

我们希望测试数据库操作,传出的是一个字符串,JSON对象即可,所以需要使用@RestController

2.1 先导入starter-web依赖

(如果你创建项目的时候,加入了web依赖,可以不用添加)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2 创建Controller类

@RestController
public class JDBCController {

    @Autowired
    JdbcTemplate jdbcTemplate;
    //查询数据库信息
    @RequestMapping("/userlist")
    public List<Map<String,Object>> userList(){
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
}

2.3 启动,测试

2

整合Druid

1.导入依赖

<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.3</version>
</dependency>

2.配置文件引入

    #druid配置
    #配置初始化大小/最小/最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
    #获取连接等待超时时间
    maxWait: 60000
    #间隔多久进行一次检测,检测需要关闭的空闲连接
    timeBetweenEvictionRunsMillis: 60000
    #一个连接在池中最小生存的时间
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
    poolPreparedStatements: false
    maxPoolPreparedStatementPerConnectionSize: 20
      #监控统计拦截的filters,stat:监控统计;log4j:日志记录;wall:防御sql注入;如果启用log4j记得添加依赖
    filters: stat,wall,log4j
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.导入Log4j

<!-- log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

4.整合Druid

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource DruidDataSource(){
        return new DruidDataSource();
    }
}

5.加入后台监控功能

//后台监控功能:web.xml
// 因为SpringBoot 内置了servlet容器,所以没有web.xml  替代方法:ServletRegistrationBean
@Bean
public ServletRegistrationBean a(){
    ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
    // 后台需要有人登录,账号密码配置
    HashMap<String, String> initParameters = new HashMap<>();
    //增加配置   登录key 是固定的 loginUsername   loginPassword
    initParameters.put("loginUsername","admin");
    initParameters.put("loginPassword","123456");
    //允许谁可以访问
    initParameters.put("allow","");
    //禁止谁能访问  initParameters.put("用户名","地址");
    bean.setInitParameters(initParameters);  //设置初始化参数
    return bean;
}
3 4

6.加入过滤器

public FilterRegistrationBean webStatFilter(){
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());
    //可以过滤的请求
    HashMap<String, String> initParameters = new HashMap<>();
    initParameters.put("exclusions","*.js,*.css,/druid/*");
    bean.setInitParameters(initParameters);
    return bean;
}

整合Mybatis

这里我新创建的一个新的SpringBoot项目,这次导入web和上面sql中的那两个依赖。

1.导入依赖

该依赖不是SpringBoot官方,是专门用来整合Mybatis的。

<!-- mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

2.加入配置

spring.datasource.username=root
spring.datasource.password=148729
spring.datasource.url=jdbc:mysql://localhost:3306/mybatistest?serverTime=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3.创建POJO实体类

public class User {
    private Integer id;
    private String name;
    private String pwd;
    // toString()方法
    // Get/Set方法
    // 有参/无参方法
}

4.创建mapper类

在SpringBoot中,mapper包下只创建Mapper接口即可

// 这个注解表示了这是一个mybatis的mapper  类:Dao
@Mapper
@Repository   //注入到Spring容器中
public interface UserMapper {
    List<User> queryUserList();
    User queryUserById(int id);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
}

5.创建mapper.xml

创建路径为:resources/mybatis/mapper

<?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.zc.mapper.UserMapper">
    <select id="queryUserList" resultType="User">
        select * from user;
    </select>
    <select id="queryUserById" resultType="User" parameterType="int">
        select * from user where id=#{id}
    </select>
    <insert id="addUser" parameterType="User">
        insert into user(id,name,pwd) values (#{id},#{name},#{pwd})
    </insert>
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
    <update id="updateUser" parameterType="User">
        update user set name = #{name},pwd=#{pwd} where id = #{id}
    </update>

</mapper>

6.起别名、注册mapper.xml

如果想要上面语句中的User生效的话,需要进行起别名:

# 整合mybatis
#起别名
mybatis.type-aliases-package=com.zc.pojo  
#注册classpath:mybatis/mapper路径下的所有mapper.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

7.创建Controller类

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/queryUserList")
    public List<User> queryUserList(){
        List<User> users = userMapper.queryUserList();
        for (User user : users) {
            System.out.println(user);
        }
        return users;
    }
}

8.测试

直接开启启动器,进入网页即可

5

个人博客为:
MoYu's HomePage
MoYu's Gitee Blog

posted @ 2021-03-31 22:46  MoYu-zc  阅读(61)  评论(0编辑  收藏  举报