Spring JDBC基础知识和简单实例

一、Spring JDBC 的概念
在我们平常使用JDBC数据库时,需要频繁的建立数据库的连接,调用执行数据库语句,以及处理大量的异常信息,为工作和学习增加了很多不必要的代码冗余,所以我们可以使用Spring JDBC 框架,负责所有的低层细节,从开始打开连接,准备和执行 SQL 语句,处理异常,处理事务,到最后关闭连接。
二、Spring JDBC 的配置
Spring JDBC有四个组成部分:core(核心包),dataSource(数据源包),object(对象包),support(支持包)。具体如下:
在这里插入图片描述
想要使用Spring JDBC,我们首先需要导入这几个jar包:

  • aspectjrt.jar
  • aspectjweaver.jar
  • com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar
  • com.springsource.org.apache.commons.pool-1.5.3.jar
  • mysql-connector-java-5.0.8-bin.jar
  • 以及Spring-webmvc的基础包。

代码的基本结构如下:
在这里插入图片描述
我们需要在spring.xml文件中配置数据库类型,连接对象,数据源,以及代理事务的通知和属性。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">

    <!--自动扫描上下文-->
<context:component-scan base-package="cn.zc.*"></context:component-scan>

    <!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/stu1"></property>
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
</bean>
    <!--配置jdbc模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
</bean>
    <!--JDBC模板-->
    <!--事务管理-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!--事务的通知和属性-->
<tx:advice id="txadvice" transaction-manager="txManager">
    <tx:attributes>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="update" propagation="REQUIRED"/>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>
    
<aop:config>
    <aop:pointcut expression="execution(* cn.zc.dao.Impl.*.*(..))" id="services"></aop:pointcut>
    <aop:advisor advice-ref="txadvice" pointcut-ref="services"></aop:advisor>
</aop:config>
</beans>

注:数据源中的内容与我们之前使用的数据库连接方法中使用的数据一致。

创建实体类:

package cn.zc.domain;

public class Student {
    public int id;
    public String name;
    public String sex;
    public int score;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public Student() {
    }

    public Student(int id, String name, String sex, int score) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", score=" + score +
                '}';
    }
}

Dao层的接口以及实现类:
接口:

package cn.zc.dao;

import cn.zc.domain.Student;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface StudentDao {

    public List<Student> findAllStu();
    public void updateStu(Student stu);
}

实现类:

package cn.zc.dao.Impl;

import cn.zc.dao.StudentDao;
import cn.zc.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

//仓库
@Repository
public class StudentDaoImpl implements StudentDao {
//自动装配
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    @Override
    public List<Student> findAllStu() {

        return jdbcTemplate.query("select *from stu", new RowMapper<Student>() {
            @Nullable
            @Override
            public Student mapRow(ResultSet rs, int num) throws SQLException {
                Student student = new Student();
                student.setId(rs.getInt(1));
                student.setName(rs.getString(2));
                student.setSex(rs.getString(3));
                student.setScore(rs.getInt(4));
                return student;
            }
        });
    }

    @Override
    public void updateStu(Student stu) {
        jdbcTemplate.update("update stu set score=? where id=?",stu.getScore(),stu.getId());
    }
}

service层的内容:

package cn.zc.service;

import cn.zc.dao.StudentDao;
import cn.zc.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService  {
@Autowired
    private StudentDao studentDao;

    public StudentDao getStudentDao() {
        return studentDao;
    }

    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }


    public List<Student> findAllStu(){
        return studentDao.findAllStu();
    }

    public void updateStu(Student stu) {
        studentDao.updateStu(stu);
    }
}

测试类:

package cn.zc.test;

import cn.zc.domain.Student;
import cn.zc.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class test {
    public static void main(String[] args) {
        test1();

    }

    private static void test1() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        StudentService stu = ctx.getBean("studentService", StudentService.class);
        List<Student> allStu = stu.findAllStu();
        for (Student student : allStu) {
            System.out.println(student.getName());
        }
    }

}

可能出现的报错:

Can not find com.mysql.jdbc.Driver.

这是没有导入数据库连接包mysql-connector-java-5.0.8-bin.jar导致的。

Could not open JDBC Connection for transaction; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Unknown database ‘stu’)

这是因为spring.xml文件中数据源里关键字url配置的数据库名称找不到而出现的报错。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值