Briefly describe the JDBC framework in Spring

Briefly describe the Spring JDBC framework

1. Overview of the JDBC framework
Because the JDBC operation process is more troublesome and most of the operation steps are relatively fixed, many frameworks have encapsulated and optimized it. The well-known Spring framework also encapsulates JDBC simply.
The Spring framework provides a JdbcTemplate class to simplify the development of JDBC. Its characteristics are: simple and convenient. This technology is commonly known as Spring JDBC technology.
Spring JDBC is understood to mean that the Spring framework encapsulates and optimizes the persistence layer JDBC operation, turning cumbersome into simple and practical, that is, solving the technical problems of the persistence layer.

When using an ordinary JDBC database, it will be troublesome to write unnecessary code to handle exceptions, open and close database connections, etc. But the Spring JDBC framework is responsible for all the low-level details, from opening the connection at the beginning, preparing and executing SQL statements, handling exceptions, handling transactions, and closing the connection at the end.

So when getting data from the database, what you do is define the connection parameters, specify the SQL statement to be executed, and complete the required work for each iteration.
2. Spring JDBC example
Want to understand the related concepts of the Spring JDBC framework with jdbc template class, let us write a simple example to implement simple query operations.
This is my project structure
Insert picture description here

(1) Create a database table. My table data is as follows:
Insert picture description here
(2) Create an entity class

package cn.tb.entity;
public class City {
    
    
    private int cid;
    private String cname;
    private int pid;
    public int getCid() {
    
    
        return cid;
    }
    public void setCid(int cid) {
    
    
        this.cid = cid;
    }
    public String getCname() {
    
    
        return cname;
    }
    public void setCname(String cname) {
    
    
        this.cname = cname;
    }
    public int getPid() {
    
    
        return pid;
    }
    public void setPid(int pid) {
    
    
        this.pid = pid;
    }
    public City(int cid, String cname, int pid) {
    
    
        this.cid = cid;
        this.cname = cname;
        this.pid = pid;
    }
    public City() {
    
    
    }
}

(3) Create an interface

package cn.tb.dao;

import cn.tb.entity.City;
import java.util.List;

public interface CityDao {
    
    
    public List<City> findCnameAll();  //查询所有城市

(4) The interface implementation class uses the JdbcTemplate class and the
JdbcTemplate class.
Spring encapsulates the operation of the database in depth on the jdbc. Using the spring injection function, the DataSource can be registered in the JdbcTemplate.
JdbcTemplate mainly provides the following five types of methods:
execute method: can be used to execute any SQL statement, generally used to execute DDL statements;
update method and batchUpdate method: update method is used to execute new, modified, and deleted statements; batchUpdate method is used to Execute batch related statements;
query method and queryForXXX methods: used to execute query related statements;
call method: used to execute stored procedures and function related statements.

package cn.tb.dao.impl;

import cn.tb.dao.CityDao;
import cn.tb.entity.City;
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 CityImpl implements CityDao{
    
    
    //JdbcTemplate 类
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
    
    
        return jdbcTemplate;
    }

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

    @Override
    public List<City> findCnameAll() {
    
    
        return jdbcTemplate.query("select * from city",new RowMapper(){
    
    
            @Nullable
            @Override
            public City mapRow(ResultSet rs, int i) throws SQLException {
    
    
                City city = new City();
                city.setCid(rs.getInt(1));
                city.setCname(rs.getString(2));
                city.setPid(rs.getInt(3));
                return city;
            }
        });
    }

(5)service

package cn.tb.service;

import cn.tb.dao.CityDao;
import cn.tb.entity.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CityService {
    
    
    @Autowired
    private CityDao cityDao;

    public CityDao getCityDao() {
    
    
        return cityDao;
    }

    public void setCityDao(CityDao cityDao) {
    
    
        this.cityDao = cityDao;
    }

    public List<City> findCnameAll(){
    
    
        return cityDao.findCnameAll();
    }

    public void update(City cid){
    
    
        cityDao.update(cid);
    }
}

(6) Configure the XML file (this is also the most important step)

<?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/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                           http://www.springframework.org/schema/context
                           https://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
                           ">
    <!--自动扫描上下文包      自动扫描cn.tb下的所有包-->
    <context:component-scan base-package="cn.tb.*" />  
    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
         <!--加载mysql驱动-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <!--获取数据库连接     jqueryajaxdemo 数据库名-->
        <property name="url" value="jdbc:mysql://localhost:3306/jqueryajaxdemo?serverTimezone=UTC" />
         <!--获取数据库账号-->
        <property name="username" value="root" />
         <!--获取数据库密码-->
        <property name="password" value="root" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--事务管理-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </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 id="services" expression="execution(* cn.tb.dao.impl.*.*(..))" />
        <aop:advisor advice-ref="txadvice" pointcut-ref="services" />
    </aop:config>
</beans>

(7) Test

package cn.tb.test;

import cn.tb.entity.City;
import cn.tb.service.CityService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext alc = new ClassPathXmlApplicationContext("Spring.xml");
        CityService ct = alc.getBean("cityService", CityService.class);
        List<City> list = ct.findCnameAll();
        for (City c : list) {
    
    
            System.out.println(c.getCname());
        }
    }
}

(8) Test results
Insert picture description here

Guess you like

Origin blog.csdn.net/tan1024/article/details/114989754