SpringBoot與數據訪問

SpringBoot與數據訪問

1. JDBC

1.1 創建SpringBoot項目

使用Spring Initializr創建SpringBoot項目,勾選Spring Web(Web)、JDBC、MySQL三項:
在這裏插入圖片描述

生成後pom.xml是這樣的:

<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>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

1.2 修改配置

修改配置文件,這裏只配置了基礎的幾項屬性,具體的屬性可以在org.springframework.boot.autoconfigure.jdbc.DataSourceProperties(SpringBoot2以上的版本)

中查看,或者說編譯器一般也會帶自動帶有相關提示。

src/main/resources/application.yml:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/db_user?serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
@ConfigurationProperties(
    prefix = "spring.datasource"
)
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
    private ClassLoader classLoader;
    private String name;
    private boolean generateUniqueName;
    private Class<? extends DataSource> type;
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    private String jndiName;
    private DataSourceInitializationMode initializationMode;
    private String platform;
    private List<String> schema;
    private String schemaUsername;
    private String schemaPassword;
    private List<String> data;
    private String dataUsername;
    private String dataPassword;
    private boolean continueOnError;
    private String separator;
    private Charset sqlScriptEncoding;
    private EmbeddedDatabaseConnection embeddedDatabaseConnection;
    private DataSourceProperties.Xa xa;
    private String uniqueName;
    //...
}

1.3 測試

在測試類裏注入數據源並測試:

@SpringBootTest
class TestjdbcApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println("********"+dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println("********"+connection);
        connection.close();
    }

}

輸出結果如下:

********class com.zaxxer.hikari.HikariDataSource
********HikariProxyConnection@256522893 wrapping com.mysql.cj.jdbc.ConnectionImpl@8d8f754

表明已經連接成功

結論:

  • 默認是用com.zaxxer.hikari.HikariDataSource作爲數據源;
  • 數據源的相關配置都在DataSourceProperties裏面;
  • 使用時直接注入JdbcTemplate使用即可

2. 整合Druid數據源

2.1 導入依賴

使用Spring Initializr創建項目,勾選Spring Web、MySQL、jdbc三項

初始化後pom文件:

        <!-- web場景啓動器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mysql驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--jdbcTemplate -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- druid數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.26</version>
        </dependency>

2.2 在 src/main/resources 目錄下創建 druid.properties 文件

#數據庫設置
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_user?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=333666999520
#--------------------------
# 下面爲連接池的補充設置,應用到上面所有數據源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=1
spring.datasource.maxActive=50
# 配置獲取連接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,並且指定每個連接上PSCache的大小
spring.datasource.poolPreparedStatements=false
#spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控界面sql無法統計
spring.datasource.filters=slf4j
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合併多個DruidDataSource的監控數據
#spring.datasource.useGlobalDataSourceStat=true
  • 驅動名稱、url、用戶名、密碼需要根據自身使用的數據庫以及數據庫版本等情況進行更改

2.3爲Druid數據源創建一個配置類

@Configuration可以使SpringBoot知道這是一個配置類

@PropertySource用於指定配置文件,若不指定則SpringBoot會從全局配置文件讀取配置。

導入druid數據源
@Configuration
@PropertySource(value="classpath:druid.properties")
public class DruidConfig {

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

    //配置Druid的監控
    //1、配置一個管理後臺的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默認就是允許所有訪問
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一個web監控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

2.4寫一個Controller來測試一下

@Controller
public class HelloController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/hello")
    @ResponseBody
    public List<Map<String,Object>> hello(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from tb_user");
        return list;
    }
}

訪問 http://localhost:8080/hello,從數據庫獲取數據成功

在這裏插入圖片描述

訪問 http://localhost:8080/druid/

在這裏插入圖片描述
輸入上面配置的用戶名與密碼登錄:

在這裏插入圖片描述

3. 整合MyBatis

3.1 前期工作

3.1.1導入依賴

勾選web、mybatis和mysql幾項,生成pom如下:

	    <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.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

3.1.2配置數據源相關屬性(參考1或2)

驅動類名稱、用戶名、密碼、url等幾項基本屬性必須配置

3.1.3 給數據庫建表

CREATE DATABASE db_user;
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `tel` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('偉大的開發者', '123456');
INSERT INTO `tb_user` VALUES ('二釗', '164110');

3.1.4 創建JavaBean

public class User {
    String name;
    String tel;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public User(){

    }

    public User(String name, String tel) {
        this.name = name;
        this.tel = tel;
    }
}

3.2 註解版

使用註解編寫sql,這裏需要注意的是不要漏了@Mapper,否則無法加入Spring容器。當Mapper文件多的時候,每一個Mapper都需要加入@Mapper註解會很麻煩,所以可以在SpringBoot主類上加上@MapperScan(包名)註解,開啓包掃描。

@Mapper
public interface UserMapper {

    @Select("select * from tb_user")
    public List<User> getAllUsers();

    @Select("select * from tb_user where name=#{name}")
    public User getUserByName(String name);

    @Delete("delete from tb_user where name=#{name}")
    public int deleteUserByName(String name);

    @Update("update tb_user set tel=#{tel} where name=#{name}")
    public int updateUser(User user);

    @Insert("insert into tb_user values(#{name},#{tel})")
    public int insertUser(User user);
}

根據實際需要自定義MyBatis的配置規則:給容器中添加一個ConfigurationCustomizer;

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

3.3 配置文件版

在全局配置文件裏指定mybatis的配置文件與sql映射文件的位置,其他的按照原mybatis規則去做就ok了

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

更多使用參照

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

3.4 測試

@Controller
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/users")
    @ResponseBody
    public List<User> users(){
        return userMapper.getAllUsers();
    }

    @GetMapping("/user/{name}")
    @ResponseBody
    public User user(@PathVariable("name")String name){
        return userMapper.getUserByName(name);
    }

    @RequestMapping("/user/del/{name}")
    @ResponseBody
    public int deluser(@PathVariable("name")String name){
        return userMapper.deleteUserByName(name);
    }

    @RequestMapping("/user/update")
    @ResponseBody
    public int updateUser(User user){
        return userMapper.updateUser(user);
    }

    @RequestMapping("/user/add")
    @ResponseBody
    public int addUser(User user){
        return userMapper.insertUser(user);
    }
}

在這裏插入圖片描述

在這裏插入圖片描述

發佈了107 篇原創文章 · 獲贊 163 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章