Spring框架+jdbcTemplate實現增刪改查功能

SpringMVC架構(Model(實體類),Service,Controller層)

Controller(接收參數調用業務層)–>Service(調用持久層,處理業務邏輯)–>Dao(與數據庫交互)

1. IOC(控制反轉是一種設計思想而不是技術)

DI(依賴註入):是IOC思想的一種技術實現

IOC容器是Spring提供的保存Bean對象的容器

Bean管理操作

1.Xml + 註解

2.javaConfig + 註解

通過xml配置Bean:TODO:

通過javaConfig 配置Bean:TODO:

通過註解配置Bean:TODO:

2. AOP(面向切面)

面向切面的程序設計思想。橫向的調用。

eg:一個日志的功能,很多的功能模塊都需要去使用,可以寫一個切面去做這個事情。

使用@Aspect來標記一個普通類為切面。

連接點:比如說日志需要作用的方法。

目標對象:日志需要使用的對象。

1. 添加依賴

<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.7</version>
    <scope>runtime</scope>
</dependency>

2.demo練習

需求:SpringIOC + JDBCTemplate實現簡單的數據庫操作

1.新建Maven項目並引入Spring核心4依賴

<!--Spring的4個基礎jar包(容器包)-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.3.1</version>
        </dependency>

jdbc依賴

<!--Spring整合jdbc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.6</version>
        </dependency>

        <!--mysql驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

junit5

<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.2</version>
            <scope>test</scope>
        </dependency>

2. 創建SpringConfig配置文件(通過JavaConfig方式註入bean)

創建SpringConfig類,添加@Configuration標記為配置類。

配置數據源和JDBCTemplateBean

/**
 * @author YonC
 * @date 2021/9/2
 */
@Configuration
public class SpringConfig {
    @Bean
    public DataSource dataSource() {
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=ture&charactorEncoding=utf-8&serverTimezone=UTC");
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

3.創建MVC架構並創建與數據庫字段對應的實體類對象

實體類:StudentPO

public class StudentPO {
    private Long id;
    private String name;
    private String age;

    public StudentPO() {
    }

    public StudentPO(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public StudentPO(Long id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "StudentPO{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

4. 編寫Dao層

面向接口編程,首先定義Dao層的規范接口,定義瞭增刪改查4種方法

/**
 * @author YonC
 * @date 2021/9/2
 */
public interface StudentDao {
    void addStudent(StudentPO student);

    void delStudentById(Long id);

    void updateStudent(StudentPO student);

    List<StudentPO> selectStudent();
}

接口的實現

@Repository註解將StudentDao註入IOC容器

@Autowired自動裝配JdbcTemplate對象,JdbcTemplate對象已經在SpringConfig文件中實例化

/**
 * @author YonC
 * @date 2021/9/2
 */
@Repository
public class StudentDaoImpl implements StudentDao {


    @Autowired
    JdbcTemplate jdbcTemplate;

    /*
     * 增加Student
     * */
    @Override
    public void addStudent(StudentPO student) {
        jdbcTemplate.update("insert into student (name,age) values (?,?)", student.getName(), student.getAge());
    }

    /*
     * 刪除Student
     * */
    @Override
    public void delStudentById(Long id) {
        jdbcTemplate.update("delete from student where id=?", id);
    }

    /*
     * 修改Student
     * */
    @Override
    public void updateStudent(StudentPO student) {
        String sql = "UPDATE student SET name=?,age=? where id = ? ";
        Object[] args = {student.getName(), student.getAge(), student.getId()};
        jdbcTemplate.update(sql, args);
    }

    /*
     * 查詢
     * */
    @Override
    public List<StudentPO> selectStudent() {
        String sql = "select id,name,age from student";
        return this.jdbcTemplate.query(sql, (rs, index) -> {
            StudentPO student = new StudentPO();
            student.setId(rs.getLong("id"));
            student.setName(rs.getString("name"));
            student.setAge(rs.getString("age"));
            return student;
        });
    }
}

5. Dao與數據庫的增刪改查已經實現,使用Service層去調用Dao層的方法。

首先定義Service層的接口

/**
 * @author YonC
 * @date 2021/9/2
 */
public interface StudentService {

    void addStudent(StudentPO student);

    void delStudentById(Long id);

    void updateStudent(StudentPO student);

    List<StudentPO> selectStudent();
}

接口實現

@Service將對象聲明IOC容器中

@Autowired自動裝配IOC容器中的StudentDaoStudentDao對象初始化

/**
 * @author YonC
 * @date 2021/9/2
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentDao studentDao;

    @Override
    public void addStudent(StudentPO student) {
        studentDao.addStudent(student);
    }

    @Override
    public void delStudentById(Long id) {
       studentDao.delStudentById(id);
    }

    @Override
    public void updateStudent(StudentPO student) {
       studentDao.updateStudent(student);
    }

    @Override
    public List<StudentPO> selectStudent() {
        return studentDao.selectStudent();
    }
}

6. 使用Junit5單元測試測試

首先通過IOC容器拿到StudentService對象

private AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    // 通過Spring的IOC容器
    private StudentService studentService = applicationContext.getBean(StudentService.class);

測試

/**
 * @author YonC
 * @date 2021/9/2
 */
class StudentServiceImplTest {

    private AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    // 通過Spring的IOC容器
    private StudentService studentService = applicationContext.getBean(StudentService.class);
    @Test
    public void testAddStudent() {

        studentService.addStudent(new StudentPO("zahngsna", "999"));
        System.out.println("添加成功!");
    }

    @Test
    public void testDelStudent() {
        studentService.delStudentById(3L);
        System.out.println("刪除成功!");
    }

    @Test
    public void testUpdateStudent() {
        //將id為3的Student的name修改為"wang",age修改為21
        studentService.updateStudent(new StudentPO(1L,"wang","28"));
        System.out.println("修改成功!");
    }

    @Test
    public void testSelectStudent() {
        studentService.selectStudent().forEach(System.out::println);
    }

}

到此這篇關於Spring框架+jdbcTemplate實現增刪改查功能的文章就介紹到這瞭,更多相關Spring jdbcTemplate增刪改查內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: