(7.1)Spring框架——Spring JdbcTemplate

news/2024/7/7 6:38:55

目录

一、概述

(一)、是配置数据库的Bean。

(二)、配置JDBC模板。

(三)、配置注入类。

二、步骤

(一)编写实体类。

(二)编写接口。

(三)编写接口实现类。

(四)编写测试类。

(五)编写XML配置文件

三、举例

(一)、定义一个实体类,在数据库里面有对象的表。名为:Account

(二)、定义一个接口,名为:AccountDao 

(三)、定义一个实现类。名为:AccountDaoImpl

(四)、创建测试类,名为:JdbcTemplateTest 

(五)、配置xml文件,数据源Bean,jdbcTemplate的Bean,Dao层的Bean。



一、概述

综述:利用Spring JdbcTemplate类里面的方法,进行增删改查的操作。

细节描述:在xml里面的配置。

(一)、是配置数据库的Bean。

(二)、配置JDBC模板。

(三)、配置注入类。

1、首先定义数据源。数据源是配置数据库的连接。id名称为:dataSource。通俗的讲:就是把数据库连上Spring框架。

2、配置第二个Bean,id为:jdbcTemplate。把dataSource注入到jdbcTemplate中。通俗的讲:就是Spring里面封装了一些方法,可以进行增删改查。Spring框架封装了这些方法。

3、配置第三个Bean,id为:accountDao,把jdbcTemplate注入这个Bean中。注入后在这个实例类中就可以用了。通俗的讲:这一层就是沟通前后端的。注入后就可以使用。

二、步骤

(一)编写实体类。

(二)编写接口。

(三)编写接口实现类。

(四)编写测试类。

(五)编写XML配置文件

三、举例

(一)、定义一个实体类,在数据库里面有对象的表。名为:Account

package com.stx.chapter04.jdbc;

public class Account {
    private Integer id;
    private String userName;
    private Double balance;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

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

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", balance=" + balance +
                '}';
    }
}

(二)、定义一个接口,名为:AccountDao 

package com.stx.chapter04.jdbc;

import java.util.List;

public interface AccountDao {
//    添加
    public int addAccount(Account account);
//    更新
    public int updateAccount(Account account);
//    删除
    public int deleteAccount(int id);
//    通过id查询
    public Account findAccountById(int id);
//    查询所有账户
    public List<Account> findAllAccount();
}

(三)、定义一个实现类。名为:AccountDaoImpl

package com.stx.chapter04.jdbc;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class AccountDaoImpl implements AccountDao{
//    声明JdbcTemplate属性以及setter方法
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
//   添加账户
    @Override
    public int addAccount(Account account) {
//        定义SQL
        String sql = "insert into account(username,balance) values(?,?)";
//        定义数组来储存SQL语句中的参数
        /*
        * 定义一个数组,把对象获取出来。对象是方法参数传递进来的。
        * */
        Object[] obj = new Object[]{
                account.getUserName(),
                account.getBalance()
        };
        int num = this.jdbcTemplate.update(sql,obj);
        return num;
    }

//    更新账户
    @Override
    public int updateAccount(Account account) {
//        定义SQL
        String sql = "update account set username=?,balance=?where id=?";

        Object[] params = new Object[]{
          account.getUserName(),
          account.getBalance(),
          account.getId()
        };
        int num = this.jdbcTemplate.update(sql,params);
        return num;
    }
//删除账户
    @Override
    public int deleteAccount(int id) {
//        定义SQL
        String sql ="delete from account where id = ?";
        int num = this.jdbcTemplate.update(sql,id);
        return num;
    }
//查询一个数据
    @Override
    public Account findAccountById(int id) {
//        定义sql语句
        String sql = "select * from account where id = ?";
//        创建一个新的对象BeanPropertyRowMapper
        RowMapper<Account>  rowMapper = new BeanPropertyRowMapper<Account>(Account.class);
//        将id 绑定到sql语句中,并通过RowMapper返回一个Object类型的单行记录。
        return this.jdbcTemplate.queryForObject(sql, rowMapper,id);
    }
//查询所有数据
    @Override
    public List<Account> findAllAccount() {
//        定义sql语句。
        String sql = "select * from account";
//        创建一个新的对象BeanPropertyRowMapper
        RowMapper<Account> rowMapper =
                new BeanPropertyRowMapper<Account>(Account.class);
//执行静态的sql查询,并通过RowMapper返回结果。
        return this.jdbcTemplate.query(sql,rowMapper);
    }
}

(四)、创建测试类,名为:JdbcTemplateTest 

package com.stx.chapter04.jdbc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class JdbcTemplateTest {
    /*public static void main(String[] args) {
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jt =(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        jt.execute("CREATE table message(id int PRIMARY KEY,name CHAR(20),sex CHAR(4),dress CHAR(80))");
        System.out.println("信息表message创建成功!");
    }*/
//    这是导入的单元测试。Junit4开源框架。
    @Test
    public void mainTest(){/*
        特别提醒,如果是放在src下面的其他包,需要将其整个包名暴露出来。
        例如 String XmlPath = "com\stx\chapter04\jdbc\applicationContext.xml";
        在传递给ClassPathXmlApplicationContext(XmlPath);
*/
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jt =(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        jt.execute("CREATE table account(id int PRIMARY KEY auto_increment,username varchar(20),balance double)");
        System.out.println("信息表message创建成功!");
    }
    @Test
    public void addAccountTest(){
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDao accountDao =(AccountDao) applicationContext.getBean("accountDao");
        Account account = new Account();
        account.setUserName("Tom");
        account.setBalance(1200.00);
        int num = accountDao.addAccount(account);
        if (num>0){
            System.out.println("成功插入!"+num+"条数据");
        }else {
            System.out.println("插入操作失败!");
        }
    }
    @Test
    public void updateAccountTest(){
        ApplicationContext app=
                new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDao accountDao =(AccountDao) app.getBean("accountDao");
        Account account = new Account();
        account.setId(102);
        account.setUserName("Tom");
        account.setBalance(2001.00);
//        调用方法,把对象存入跟新语句。进入另外一个类的方法,
        int num = accountDao.updateAccount(account);
        if (num>0){
            System.out.println("成功修改!"+num+"条数据");
        }else {
            System.out.println("插入操作失败!");
        }
    }
    @Test
    public void deleteAccountTest(){
        ApplicationContext application=
                new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDao accountDao =(AccountDao) application.getBean("accountDao");
        int num = accountDao.deleteAccount(102);
        if (num>0){
            System.out.println("删除成功!"+num+"条数据");
        }else {
            System.out.println("删除操作失败!");
        }
    }
//
    @Test
    public void findAccountByIdTest(){
//        加载配置文件
        ApplicationContext application=
                new ClassPathXmlApplicationContext("applicationContext.xml");
//        获取AccountDao实例
        AccountDao accountDao =(AccountDao) application.getBean("accountDao");
    Account account=accountDao.findAccountById(103);
        System.out.println(account);
    }
    @Test
    public void findAccountAllTest(){
//        加载配置文件
        ApplicationContext application=
                new ClassPathXmlApplicationContext("applicationContext.xml");
//        获取AccountDao实例
        AccountDao accountDao =(AccountDao) application.getBean("accountDao");
        List<Account> accounts = accountDao.findAllAccount();
        for (Account act:accounts){
            System.out.println(act);
        }
    }

}

(五)、配置xml文件,数据源Bean,jdbcTemplate的Bean,Dao层的Bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    配置数据源,连接数据库。-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!--        数据库驱动-->
<!--        property都是通过setter赋值,后面的是要设置的参数-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<!--        连接数据库的url  特别提醒:jdbc:mysql//服务器地址/数据库名-->
<!--       value="jdbc:mysql://localhost/db1" 这个db1要改成你的数据库库名。-->
        <property name="url" value="jdbc:mysql://localhost/db1"></property>
<!--        连接数据库的用户名-->
        <property name="username" value="root"></property>
<!--        连接数据库的密码-->
        <property name="password" value="123456"></property>
    </bean>

<!--    配置JDBC模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--            默认必须使用数据源。-->
        <!--        ref引用上一个bean的对象。通俗的说:就是把前面一个Bean的实例注入到当前这个Bean中。-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--    定义id为accountDao的Bean-->
    <bean id="accountDao" class="com.stx.chapter04.jdbc.AccountDaoImpl">
<!--        将jdbcTemplate实例对象,注入到account实例中,然后就在Account存在,并被引用.-->
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
</beans>

 


http://www.niftyadmin.cn/n/4557282.html

相关文章

求解一道Java面试题。

答案是E 当demo null; 不会马上就回收 因为java垃圾回收机制是根据自身内存情况而定

Materialize快速入门教程

https://materializecss.com/ https://github.com/Dogfalo/materialize http://www.materializecss.cn/ 1&#xff0c;下载 http://materializecss.cn/bin/materialize-v0.97.8.zip <!-- Compiled and minified CSS --> <link rel"stylesheet" href"ht…

(8)Spring框架——TransactionManager事务管理(基于XML方法的声明事务)

目录 一、XML声名事务概述 &#xff08;一&#xff09;PlatformTransactionManager &#xff08;二&#xff09;TransactionDefinition &#xff08;三&#xff09;TransactionStatus 二、举例 &#xff08;一&#xff09;、例子关键点描述 1、要在XML配置文件里面添加命…

BZOJ 2342 [Shoi2011]双倍回文(manacher+堆+set)

题意 N<500000 题解 维护一个set可以用堆来解决。 1 #include<iostream>2 #include<cstring>3 #include<cstdio>4 #include<cmath>5 #include<algorithm>6 #include<set>7 #include<queue>8 using namespace std;9 const int N50…

c.k死了没.

||| over了 很神奇 别去猜测时间能够说明一切问题&#xff0e;

(9)Spring框架——MyBatis的学习

目录 一、概述 &#xff08;一&#xff09;项目准备工作 &#xff08;二&#xff09;项目结构描述 &#xff08;三&#xff09;具体作用概述 二、举例 &#xff08;一&#xff09;步骤 &#xff08;二&#xff09;实例 一、概述 &#xff08;一&#xff09;项目准备工作…

一个C++编程问题

而现在的方法是 按引用调用 (call by reference) 传递 即将实参复制给形参 如果去掉就编程 使用按值调用 (call by value) 来传递参数了 这样形参才能改变实参的值 这样实参的值不会被形参改变

HDU 2612 find a way 【双BFS】

<题目链接> 题目大意&#xff1a;两个人分别从地图中的Y 和 M出发&#xff0c;要共同在 处会面&#xff08;不止有一处&#xff09;&#xff0c;问这两个人所走距离和的最小值是多少。 解题分析&#xff1a; 就是对这两个点分别进行一次BFS&#xff0c;求出它们到每一个…