spring的简单使用(配合Druid操作数据库)

文章目录

准备数据

sql 复制代码
create database if not exists db_spring;
use db_spring;
drop table if exists tb_user;
create table if not exists tb_user
(
    id      int primary key auto_increment,
    name    varchar(10) not null unique,
    age     int,
    id_card varchar(10)
);

insert into tb_user(name, age, id_card)
    values ('张三', 23, '10001'),
           ('李四', 18, '10002'),
           ('王五', 34, '10003'),
           ('赵六', 45, '10004');

select * from tb_user;

pom.xml文件中引用需要的库

xml 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.0.12</version>
    </dependency>

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

    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
</dependencies>

准备好dao层接口和service层接口和实现类

  • dao层

    java 复制代码
    // 接口
    package com.test.dao;
    
    public interface UserDao {
        void selectAll();
    
        void selectById();
    }
  • service层

    java 复制代码
    // 接口
    package com.test.service;
    
    public interface UserService {
        void selectAll();
    
        void selectById();
    }
    
    // 实现类
    package com.test.service.impl;
    
    import com.test.dao.UserDao;
    import com.test.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    /**
     * Service注解就是标识这个类是service层的bean,spring启动的时候,就会把它放入到Ioc容器中
     * 跟这个相似还有 @Repository 和 @Controller
     */
    @Service
    public class UserServiceImpl implements UserService {
        // Autowired注解是自动装配
        @Autowired
        private UserDao userDao;
    
        @Override
        public void selectAll() {
            userDao.selectAll();
        }
    
        @Override
        public void selectById() {
            userDao.selectById();
        }
    }

准备好 jdbc.propertiesuser.properties

这里分开写,是为了练习加载多个配置文件,所以需要再resources资源文件中新建这两个配置文件

  • jdbc.properties

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql:///db_spring?useServerPrepStmts=true
    jdbc.username=root
    jdbc.password=root1234
    
  • user.properties

    name=张三
    age=23
    sex=男
    idCard=10001
    id=2
    

编写Druid的jdbcConfig配置类

java 复制代码
public class JdbcConfig {
    /**
     * 这里通过Value注解从properties配置文件中读取数据
     * 这里的前提,就是在 SpringConfig这个配置类中
     * 通过PropertySource注解引用的资源文件中的配置文件
     */
    @Value("${jdbc.driver}")
    private String driver;

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

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

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

    /**
     * 通过 注解Bean来加载第三方
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);

        return ds;
    }
}

编写spring的配置类SpringConfig

java 复制代码
package com.test.config;

import org.springframework.context.annotation.*;

/**
 * Configuration注解:设置当前类为配置类
 * ComponentScan注解:用于扫描指定路径重点bean对象
 * PropertySource注解:用于把指定的配置文件加载借来
 * Import注解:是用于导入三方的bean类进入Ioc容器
 */
@Configuration
@ComponentScan({"com.test.dao", "com.test.service"})
@PropertySource({"classpath:user.properties", "classpath:jdbc.properties"})
@Import(JdbcConfig.class)
public class SpringConfig {
}

编写Dao层的实现类的逻辑

java 复制代码
// Repository:表示是dao层的bean
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    // 自动装配
    @Autowired
    private DataSource dataSource;
    // 获取配置文件中的数据
    @Value("${id}")
    private int id;

    @Override
    public void selectAll() {
        try {
            // 操作数据库
            Connection connection = dataSource.getConnection();

            String sql = "select * from tb_user";

            PreparedStatement prepareStatement = connection.prepareStatement(sql);

            ResultSet resultSet = prepareStatement.executeQuery();

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String idCard = resultSet.getString("id_card");
                int age = resultSet.getInt("age");
                System.out.println("id:" + id + " , name:" + name + " , age:" + age + " , idCard:" + idCard);
            }
            // 释放资源
            resultSet.close();
            prepareStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void selectById() {
        try {
            Connection connection = dataSource.getConnection();

            String sql = "select * from tb_user where id = ?";

            PreparedStatement prepareStatement = connection.prepareStatement(sql);

            prepareStatement.setInt(1, id);

            ResultSet resultSet = prepareStatement.executeQuery();

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String idCard = resultSet.getString("id_card");
                int age = resultSet.getInt("age");
                System.out.println("id:" + id + " , name:" + name + " , age:" + age + " , idCard:" + idCard);
            }
            // 释放资源
            resultSet.close();
            prepareStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试类

java 复制代码
public class Main {
    public static void main(String[] args) {
        /**
         * 获取Ioc容器
         * 这里是通过SpringConfig这个配置类来获取
         */
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        // 获取bean
        UserService userService = ctx.getBean(UserService.class);

        userService.selectAll();
        System.out.println("====== selectById ======");
        userService.selectById();

    }
}

参考文献

1. 黑马程序员SSM框架教程

相关推荐
2402_8575893624 分钟前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰1 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
vvvae12342 小时前
分布式数据库
数据库
哎呦没2 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
雪域迷影2 小时前
PostgreSQL Docker Error – 5432: 地址已被占用
数据库·docker·postgresql
编程、小哥哥2 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
bug菌¹3 小时前
滚雪球学Oracle[4.2讲]:PL/SQL基础语法
数据库·oracle
逸巽散人3 小时前
SQL基础教程
数据库·sql·oracle
IT学长编程3 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
莹雨潇潇3 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器