SpringBoot学习-数据访问

SpringBoot-数据访问

jdbc

引入jdbc和MySQL的依赖

        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

数据库配置

spring:
  datasource:
    username: root
    password: 1001101
    url: jdbc:mysql://localhost:3306/loginweb?serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver

spring boot支持的数据源类型

org.apache.tomcat.jdbc.pool.DataSource
HikariDataSource
org.apache.commons.dbcp2.BasicDataSource

spring boot 2.0 默认HikariDataSource数据源
也可以自定义数据源

	@ConditionalOnMissingBean(DataSource.class)
	@ConditionalOnProperty(name = "spring.datasource.type")
	static class Generic {

		@Bean
		public DataSource dataSource(DataSourceProperties properties) {
			return properties.initializeDataSourceBuilder().build();
		}

	}
schema-*.sql建表语句,data-*.sql数据语句
使用
    schema:
      - classpath:w.sql
  指定位置
  spring boot 2.0后需要加上
   initialization-mode: always

jdbc的操作

@Controller
public class JdbcController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping("/jdbc")
    public Map<String,Object> map(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select *from bookuser");
        return list.get(0);
    }
}

整合Druid

依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

配置文件

spring:
  datasource:
    username: root
    password: 1001101
    url: jdbc:mysql://localhost:3306/loginweb?serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
#    schema:
#      - classpath:w.sql
    initialization-mode: always

    #   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Druid配置类

@Configuration
public class DruidConfig {

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

    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

        Map<String,String> map = new HashMap<>();

        map.put("loginUsername", "admin");
        map.put("loginPassword", "12345");
        bean.setInitParameters(map);
        return bean;
    }

    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,String> map = new HashMap<>();
        map.put("exclusions","*.js,*.css,/druid/*" );
        bean.setInitParameters(map);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

MyBatis

导入依赖

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

这里记一件我遇到的异常,在使用idea创建spring boot的时候,idea自动添加的MySQL依赖是这样的

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

这样在写配置文件的时候会出现
在这里插入图片描述
找不到MySQL包,这是因为scope 范围指定为runtime,runtime 依赖在运行和测试系统的时候需要,但在编译的时候不需要。所以运行时才需要,还没运行,所以idea不能找到包的路径。

依赖范围控制哪些依赖在哪些classpath 中可用,哪些依赖包含在一个应用中。让我们详细看一下每一种范围:

compile (编译范围)

compile是默认的范围;如果没有提供一个范围,那该依赖的范围就是编译范围。编译范围依赖在所有的classpath中可用,同时它们也会被打包。

provided (已提供范围)

provided 依赖只有在当JDK 或者一个容器已提供该依赖之后才使用。例如, 如果你开发了一个web 应用,你可能在编译 classpath 中需要可用的Servlet API 来编译一个servlet,但是你不会想要在打包好的WAR 中包含这个Servlet API;这个Servlet API JAR 由你的应用服务器或者servlet 容器提供。已提供范围的依赖在编译classpath (不是运行时)可用。它们不是传递性的,也不会被打包。

runtime (运行时范围)

runtime 依赖在运行和测试系统的时候需要,但在编译的时候不需要。比如,你可能在编译的时候只需要JDBC API JAR,而只有在运行的时候才需要JDBC
驱动实现。

test (测试范围)

test范围依赖 在一般的编译和运行时都不需要,它们只有在测试编译和测试运行阶段可用。

system (系统范围)

system范围依赖与provided 类似,但是你必须显式的提供一个对于本地系统中JAR 文件的路径。这么做是为了允许基于本地对象编译,而这些对象是系统类库的一部分。这样的构件应该是一直可用的,Maven 也不会在仓库中去寻找它。如果你将一个依赖范围设置成系统范围,你必须同时提供一个 systemPath 元素。注意该范围是不推荐使用的(你应该一直尽量去从公共或定制的 Maven 仓库中引用依赖)。

解决办法可以把scope去掉或者改为默认的compile即可

注解形式的mybatis

@Mapper
public interface BookMapper {

    @Select("select *from book where bookId=#{bookId}")
    public Book getBoookById(int bookId);

    @Delete("delete *from book where bookId=#{id}")
    public int deleteBookByid(int id);
	//设置useGeneratedKeys参数值为true,在执行添加记录之后可以获取到数据库自动生成的主键ID。
    @Options(useGeneratedKeys = true ,keyProperty = "bookId")
    @Insert("insert  into book(bookName) values(#{bookName})")
    public int insertBook(Book book);

    @Update("update book set bookName = #{bookName} where bookId = #{id}")
    public int updateBook(Book book);
}
@Controller
public class BookController {

    @Autowired
    BookMapper bookMapper;

    @ResponseBody
    @GetMapping("/book/{bookId}")
    public Book getBook(@PathVariable("bookId") int bookId){
        return bookMapper.getBoookById(bookId);
    }

    @ResponseBody
    @GetMapping("/book")
    public Book insertBook(Book book){
        bookMapper.insertBook(book);
        return book;
    }
}

开启驼峰命名规则

@org.springframework.context.annotation.Configuration
public class MybatisConfig implements ConfigurationCustomizer {
    @Override
    public void customize(Configuration configuration) {
        configuration.setMapUnderscoreToCamelCase(true);
    }

//    @Bean
//    public ConfigurationCustomizer configurationCustomizer(){
//       return new ConfigurationCustomizer(){
//
//            @Override
//            public void customize(Configuration configuration) {
//                configuration.setMapUnderscoreToCamelCase(true);
//            }
//        };
//    }
}

当有很多个Mapper的时候,可以在启动类上添加@MapperScan注解,该作用是会扫描指定包下的所有接口,并自动变为Mapper

@MapperScan(basePackages = "包名.mapper")

配置文件的mybatis

mybatis:
#  指定全局配置文件
  config-location: classpath:mybatis/mybatis-config.xml
#指定sql映射文件
  mapper-locations: classpath:mybatis/mapper/*.xml

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.wlj.springboot06mybatis.mapper.UserMapper">
    <select id="getUserById" resultType="com.wlj.springboot06mybatis.bean.User" parameterType="int">
        select * from bookuser where user_id = #{id}
    </select>

    <insert id="insertUser" parameterType="com.wlj.springboot06mybatis.bean.User">
        insert into bookuser values (#{user_level_id},#{user_name},#{user_password})
    </insert>
</mapper>

接口

public interface UserMapper {

    public User getUserById(int id);

    public int insertUser(User user);
}

@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable  int id){
        return userMapper.getUserById(id);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40866897/article/details/89409712