spring boot 开发(五)mariadb mysql

本文介绍了如何在Spring Boot项目中使用MariaDB数据库,包括创建表、配置数据源、添加POM依赖、创建实体类和Controller,以及进行用户管理和数据查询操作。详细步骤涵盖了从heidisql建表到应用配置、页面创建和功能测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建表

heidisql建表

CREATE TABLE myjdbctest (
id INT(8) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NULL DEFAULT NULL,
sex VARCHAR(2) NULL DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE=InnoDB
;

添加自增,且需要设置为主键,heidisql 右键–创建新索引–PRIMARY

添加pom


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

    <dependency>
      <groupId>org.mariadb.jdbc</groupId>
      <artifactId>mariadb-java-client</artifactId>
    </dependency>
<!--数据源依赖-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>


配置数据源

通过自定义配置文件配置数据源

通过@propertySource注解读取配置文件



spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mariadb://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

配置文件数据库信息

创建myConfigure.properties

jdbc.userName=root
jdbc.password=root
jdbc.url=jdbc:mariadb://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.driverClassName=com.mysql.jdbc.Driver

创建配置类


package org.example.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:/myConfiguration.properties")//加载指定的配置文件
//@ConfigurationProperties(prefix = "jdbc")//spring boot的注解,不能读取其他的配置文件,只能读取spring boot的aplication
public class JdbcConfiguration {

    @Value("${jdbc.userName}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driverClassName}")
    private String driverClassName;

    /**
     * 实例化Druid
     * @return
     */
    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }



}

创建controller测试

package org.example.controller;

import org.example.bean.Demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;


//import javax.sql.DataSource;

@Controller
public class HelloController2 {


    @Autowired
    private DataSource dataSource;

    @GetMapping("/showinfo")//spring 2.0新的注解
    public String showInfo(){

        return "OK";
    }

}

debuge查看bean是否已经加载
访问:http://localhost:8080/showinfo
在这里插入图片描述

通过@ConfigurationProperties配置文件

spring boot的注解,只能读取spring boot的application配置文件,不能读取其他的配置文件

创建实体类

package org.example.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * jdbc配置属性类
 */
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public String getUrl() {
        return url;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    private String userName;

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    private String password;

    private String url;
    private String driverClassName;


}

调整controller

package org.example.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
//@PropertySource("classpath:/myConfiguration.properties")//加载指定的配置文件
//@ConfigurationProperties(prefix = "jdbc")//spring boot的注解,不能读取其他的配置文件,只能读取spring boot的aplication
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

//    @Value("${jdbc.userName}")
//    private String userName;
//    @Value("${jdbc.password}")
//    private String password;
//
//    @Value("${jdbc.url}")
//    private String url;
//    @Value("${jdbc.driverClassName}")
//    private String driverClassName;

    @Autowired
    private JdbcProperties jdbcProperties;
    /**
     * 实例化Druid
     * @return
     */
    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(this.jdbcProperties.getUserName());
        dataSource.setPassword(this.jdbcProperties.getPassword());
        dataSource.setUrl(this.jdbcProperties.getUrl());
        dataSource.setDriverClassName(this.jdbcProperties.getDriverClassName());
        return dataSource;
    }



}

同样方式,debug,访问,也可以看到DataSource已经获取信息

@ConfigurationProperties(prefix = “jdbc”)也可以注解在方法上

添加用户

1、创建pojo

package org.example.bean;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
//
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.Id;

//@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Demo {

//    @Id@GeneratedValue
    private int id;

    private String name;

    private String sex;
}

创建页面

创建html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>你好</title>
</head>
<body>

<form th:action="@{/user/addUser}" method="post">
    <input type="text" name="name"><br/>
    <input type ="text" name="sex"><br/>
    <input type="submit" value="OK"/>
</form>
</body>
</html>

创建controller

package org.example.controller;

import org.example.bean.Demo;
//import org.example.service.DemoService;
import org.example.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Controller
@RequestMapping("/user")
public class Demo2Controller {
    @Autowired
    private DemoService demoService;

    @PostMapping("/addUser")
    public String save(Demo demo){
        try {

            this.demoService.addUser(demo);
        }catch (Exception e0){
            return "error";
        }
        return "redict:/sucess";
    }

    /**
     * 查询全部用户
     */
    @GetMapping("/findUserAll")
    public String findUserAll(Model model){
        List<Demo> list = null;
        try {

            list = this.demoService.findUserAll();
            model.addAttribute("list",list);
        }catch (Exception e0){
            System.out.println(list);
            e0.printStackTrace();
            return "error";
        }
        return "showUsers";
    }
}

持久层

package org.example.dao.impl;

import org.example.bean.Demo;
import org.example.dao.DemoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class DemoDaoImpl implements DemoDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insertUser(Demo demo) {
        String sql = "insert into myjdbctest(name,sex) values(?,?)";
        this.jdbcTemplate.update(sql,demo.getName(),demo.getSex());

    }

    @Override
    public List<Demo> findUserAll() {
        String sql = "select * from myjdbctest";

        return this.jdbcTemplate.query(sql, new RowMapper<Demo>() {
            /**
             * 做结果集的映射
             * @param resultSet
             * @param i
             * @return
             * @throws SQLException
             */
            @Override
            public Demo mapRow(ResultSet resultSet, int i) throws SQLException {
                Demo demo = new Demo();
                demo.setId(resultSet.getInt("id"));
                demo.setName(resultSet.getString("name"));
                demo.setSex(resultSet.getString("sex"));
                return demo;
            }
        });
    }
}

服务层

package org.example.service.impl;

import org.example.bean.Demo;
import org.example.dao.DemoDao;
import org.example.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DemoServiceImpl implements DemoService {


    @Autowired
    private DemoDao demoDao;

    @Override
    @Transactional
    public void addUser(Demo demo) {

        this.demoDao.insertUser(demo);
    }
    @Override
    public List<Demo> findUserAll() {
        return this.demoDao.findUserAll();
    }
}

测试

访问localhost:8080/addUser.html

查询所有用户

showUser.html

showUsers
</table>
id姓名性别操作
修改 删除
# 错误 ## pom引入spring-boot-starter-jdbc配置,但是工程中没有关于dataSource相关的配置信息,当spring创建dataSource bean因缺少相关的信息就会报错。 Action:

Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

@Controller @RestController

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值