Spring的数据库开发

#Spring中JDBC模板的作用

JDBC模板负责数据库资源管理和错误处理;

#熟悉Spring  JDBC的配置

配置数据源和jdbc模板

<?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-4.3.xsd">
    <!-- 1配置数据源 -->
    <bean id="dataSource" class=
"org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--数据库驱动 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <!--连接数据库的url -->
        <property name="url" value="jdbc:mysql://localhost:3306/spring" />
        <!--连接数据库的用户名 -->
        <property name="username" value="root" />
        <!--连接数据库的密码 -->
        <property name="password" value="root" />
    </bean>
    <!-- 2配置JDBC模板 -->
    <bean id="jdbcTemplate"
         class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 默认必须使用数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!--定义id为accountDao的Bean-->
    <bean id="accountDao" class="com.sjl.jdbc.AccountDaoImpl">
        <!-- 将jdbcTemplate注入到accountDao实例中 -->
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>
    
</beans>

# jdbcTemplate 类中几个常用方法

update()方法可以完成插入、更新、删除,并返回受影响的行数;

int update(String sql)                                               sql语句

int update(String sql,PreparedStatementSetter pss)     sql语句,预编译参数

int update(String sql,Object...args)                             sql语句,可变长参数

query()方法

List query(String sql,RowMapper rowMapper)                             sql语句,数据库中的记录,java实体的映射的对象

queryForObject(String sql,RowMapper rowMapper,Object...args)   sql语句,数据库中的记录,java实体的映射的对象,变长参数

说明:除了导入Spring的基本包,还要导入connector(驱动连接包),jdbc(连接)和ex(事务)包;

 #Account.java(实体类)
1 package com.sjl.jdbc;
public class Account {
    private Integer id; // 账户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;
    }
    public String toString() {
        return "Account [id=" + id + ", "
                + "username=" + username +
                ", balance=" + balance + "]";
    }
}
#接口的方法的实现

package com.sjl.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();
}

#接口的实现类 package com.sjl.jdbc;
import java.util.List; import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class AccountDaoImpl implements AccountDao {
    // 声明JdbcTemplate属性及其setter方法
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
// 添加账户
    public int addAccount(Account account) {
        // 定义SQL
        String sql = "insert into account(username,balance) value(?,?)";
        // 定义数组来存放SQL语句中的参数
        Object[] obj = new Object[] {
account.getUsername(),
account.getBalance()
};
        // 执行添加操作,返回的是受SQL语句影响的记录条数
        int num = this.jdbcTemplate.update(sql, obj);
        return num;
    }
    // 更新账户
    public int updateAccount(Account account) {
        // 定义SQL
        String sql = "update account set username=?,balance=? where id = ?";
        // 定义数组来存放SQL语句中的参数
        Object[] params = new Object[] {
account.getUsername(),
account.getBalance(),
account.getId()
};
        // 执行添加操作,返回的是受SQL语句影响的记录条数
        int num = this.jdbcTemplate.update(sql, params);
        return num;
    }
    // 删除账户
    public int deleteAccount(int id) {
        // 定义SQL
        String sql = "delete from account where id = ? ";
        // 执行添加操作,返回的是受SQL语句影响的记录条数
        int num = this.jdbcTemplate.update(sql, id);
        return num;
    }
    
    // 通过id查询账户数据信息
    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);
    }
    // 查询所有账户信息
    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);
    } } #测试类
package com.sjl.jdbc;
import java.util.List; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateTest {
    /**
     * 使用execute()方法建表
     */
//  public static void main(String[] args) {
//      // 加载配置文件
//      ApplicationContext applicationContext =
//       new ClassPathXmlApplicationContext("applicationContext.xml");
//      // 获取JdbcTemplate实例
//      JdbcTemplate jdTemplate =
//           (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
//      // 使用execute()方法执行SQL语句,创建用户账户管理表account
//      jdTemplate.execute("create table account(" +
//                   "id int primary key auto_increment," +
//                   "username varchar(50)," +
//                   "balance double)");
//      System.out.println("账户表account创建成功!");
//  }
    
    @Test
    public void mainTest() {
     // 加载配置文件
     ApplicationContext applicationContext =
     new ClassPathXmlApplicationContext("applicationContext.xml");
     // 获取JdbcTemplate实例
     JdbcTemplate jdTemplate =
     (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
     // 使用execute()方法执行SQL语句,创建用户账户管理表account
     jdTemplate.execute("create table account(" +
     "id int primary key auto_increment," +
     "username varchar(50)," +
     "balance double)");
     System.out.println("账户表account创建成功!");
    }     @Test
    public void addAccountTest() {
     // 加载配置文件
     ApplicationContext applicationContext =
     new ClassPathXmlApplicationContext("applicationContext.xml");
     // 获取AccountDao实例
     AccountDao accountDao =
     (AccountDao) applicationContext.getBean("accountDao");
     // 创建Account对象,并向Account对象中添加数据
     Account account = new Account();
     account.setUsername("tom");
     account.setBalance(1000.00);
     // 执行addAccount()方法,并获取返回结果
     int num = accountDao.addAccount(account);
     if (num > 0) {
     System.out.println("成功插入了" + num + "条数据!");
     } else {
     System.out.println("插入操作执行失败!");
     }
    }
    
    @Test
    public void updateAccountTest() {
     // 加载配置文件
     ApplicationContext applicationContext =
     new ClassPathXmlApplicationContext("applicationContext.xml");
     // 获取AccountDao实例
     AccountDao accountDao =
     (AccountDao) applicationContext.getBean("accountDao");
     // 创建Account对象,并向Account对象中添加数据
     Account account = new Account();
     account.setId(1);
     account.setUsername("tom");
     account.setBalance(2000.00);
     // 执行updateAccount()方法,并获取返回结果
     int num = accountDao.updateAccount(account);
     if (num > 0) {
     System.out.println("成功修改了" + num + "条数据!");
     } else {
     System.out.println("修改操作执行失败!");
     }
    }
    
    @Test
    public void deleteAccountTest() {
     // 加载配置文件
     ApplicationContext applicationContext =
     new ClassPathXmlApplicationContext("applicationContext.xml");
     // 获取AccountDao实例
     AccountDao accountDao =
     (AccountDao) applicationContext.getBean("accountDao");
     // 执行deleteAccount()方法,并获取返回结果
     int num = accountDao.deleteAccount(1);
     if (num > 0) {
     System.out.println("成功删除了" + num + "条数据!");
     } else {
     System.out.println("删除操作执行失败!");
     }
    }     @Test
    public void findAccountByIdTest() {
     // 加载配置文件
     ApplicationContext applicationContext =
     new ClassPathXmlApplicationContext("applicationContext.xml");
     // 获取AccountDao实例
     AccountDao accountDao =
     (AccountDao) applicationContext.getBean("accountDao");
     // 执行findAccountById()方法
     Account account = accountDao.findAccountById(1);
     System.out.println(account);
    }     @Test
    public void findAllAccountTest() {
     // 加载配置文件
     ApplicationContext applicationContext =
     new ClassPathXmlApplicationContext("applicationContext.xml");
     // 获取AccountDao实例
     AccountDao accountDao =
     (AccountDao) applicationContext.getBean("accountDao");
     // 执行findAllAccount()方法,获取Account对象的集合
     List<Account> account = accountDao.findAllAccount();
     // 循环输出集合中的对象
     for (Account act : account) {
     System.out.println(act);
     }
    }
}

Spring数据库开发的更多相关文章

  1. Spring - 数据库开发概述

      Spring 数据库开发 Spring 的 JDBC 模块负责数据库资源管理和镨误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从繁琐的数据库操作中解脱出来,从而将更多的精力投入到编写业 ...

  2. Spring的数据库开发

                                Spring JDBC框架操作mysql数据库 Spring中的JDBC为我们省去连接和关闭数据库的代码,我们着重关注对数据库的操作.Sprin ...

  3. 【Spring】Spring的数据库开发 - 2、Spring JdbcTemplate的常用方法(execute、update、query)

    Spring JdbcTemplate的常用方法 文章目录 Spring JdbcTemplate的常用方法 execute() update() query() 简单记录-Java EE企业级应用开 ...

  4. 【Spring】Spring的数据库开发 - 1、Spring JDBC的配置和Spring JdbcTemplate的解析

    Spring JDBC 文章目录 Spring JDBC Spring JdbcTemplate的解析 Spring JDBC的配置 简单记录-Java EE企业级应用开发教程(Spring+Spri ...

  5. 空中网招聘Java架构师、数据库开发等各类人才

    爱好网络游戏吗?爱好网站开发技术吗? 有没有想过可以成为史诗级MMO RPG<激战2>运营团队中的一员? 如果下面的职位有合适你的,加入我们吧! http://gw2.kongzhong. ...

  6. 用Spring MVC开发简单的Web应用

    这个例子是来自于Gary Mak等人写的Spring攻略(第二版)第八章Spring @MVC中的一个例子,在此以学习为目的进行记录. 问题:想用Spring MVC开发一个简单的Web应用, 学习这 ...

  7. Spring Boot——开发新一代Spring应用

    Spring官方网站本身使用Spring框架开发,随着功能以及业务逻辑的日益复杂,应用伴随着大量的XML配置文件以及复杂的Bean依赖关系.随着Spring 3.0的发布,Spring IO团队逐渐开 ...

  8. Spring MVC + Spring + Mybitis开发Java Web程序基础

    Spring MVC + Spring + Mybitis是除了SSH外的另外一种常见的web框架组合. Java web开发和普通的Java应用程序开发是不太一样的,下面是一个Java web开发在 ...

  9. Spring应用开发常见规范

    1.Spring应用开发常见包命名规范 controller:控制器 service:服务-接口 impl:服务-实现 integration sao:调用其他模块的,把feign的调用放到这个下面 ...

随机推荐

  1. rest_framework的认证系统

    1.认证模块 必须用户登录之后才能访问所有图书,才能修改图片,才能查询单个图书 2.怎么使用 其实本质上就是携带token字符串,然后后台拿到数据再取数据库进行校验,看是否有这个用户 先手写一个认证模 ...

  2. 异常处理的捕捉:try{}catch(异常类 变量)finally{最终执行}

    可以对异常进行针对性处理的方式.try{ //需要被检查的异常 }catch(异常类  变量)//该变量用于接收发生的异常{ //处理异常的代码 }finally{ //一定会被执行的代码. }

  3. 10.25 AITalkUat部署

    准备: git clone AITalkUat工程,在本地跑: 可以直接浏览器访问127.0.0.1:5000() 如果带上参数,可以得到访问的结果127.0.0.1:5000/autoservice ...

  4. JFrame绝对布局

    通过代码:setLayout(null);设置容器布局为绝对布局. 添加控件要注意:一定要设置控件具体的位置.可通过代码setLocation(20, 20)或者setBounds(0, 0, 30, ...

  5. 家庭记账本之GitHub账号注册与安装(一)

    账号注册 1.github是世纪上最大的开源代码托管网站.因为是国外网站,很多人在注册的时候因为不熟悉英语而犯了难. 2.百度搜索github进入官网.如果你已经有账号密码,那么点击右上角的sign ...

  6. jmeter BeanShell断言(一)

    原文地址https://blog.csdn.net/lijing742180/article/details/81157947 原文地址https://blog.csdn.net/zailushang ...

  7. XML反序列化遇到数字型节点值为空导致反序列化异常

    实体类: [XmlRoot("stream")] public class _30320DuisiFukuanQueryResponseModel : ResponseModelB ...

  8. 使用mysqlbinlog从二进制日志文件中查询mysql执行过的sql语句 (原)

    前提MySQL开启了binlog日志操作1. 查看MySQL是否开启binlog(进mysql操作) mysql> show variables like 'log_bin%';       2 ...

  9. c# 类一般在哪里实例化,是在类内、方法内还是其他地方?

    根据情况,你要一个页面内全局的就在类与方法之间实例化,如果一个方法需要使用这个类的对象,就在内部实例化

  10. Docker 在转发端口时的这个错误Error starting userland proxy: mkdir /port/tcp:0.0.0.0:3306:tcp:172.17.0.2:3306: input/output error.

    from:https://www.v2ex.com/amp/t/463719 系统环境是 Windows 10 Pro,Docker 版本 18.03.1-ce,电脑开机之后第一次运行 docker ...