Seventy-two, Spring and DAO operation execute ()

Spring and Dao are typical applications of Spring's two core technologies, IoC and AOP.

  • The use of the JDBC template is the application of IoC, which injects the JDBC template object into the implementation class of the Dao layer.
  • For Spring's transaction management, it is the application of AOP, and the transaction is woven into the business method of the Service layer as an aspect.

content

Spring and JDBC Templates

Method description

jdbc combat operation


Spring and JDBC Templates

        In order to avoid the complicated and lengthy code brought by using JDBC directly, Spring provides a powerful template class - JdbcTemplate to simplify JDBC operations. In addition, both the data source DataSource object and the template JdbcTemplate object can be defined in the configuration file in the form of beans, giving full play to the power of dependency injection.

concept:

What is JdbcTemplate?

        The Spring framework encapsulates JDBC and uses JdbcTemplate to facilitate database operations

        The Spring JDBC module is mainly composed of four packages, namely core (core package), dataSource (data source package), object (object package) and support (support package).

Package names illustrate
core Contains the core functions of JDBC, including the JdbcTemplate class, the sinpleJdbcInsert class, the SimpleJdbcCal1 class, and the NamedParameterJdbcTemplate class.
dataSource A utility class for accessing data sources, it has implementations of various data sources, and can test JDBC code outside the JavaEE container.
object Access the database in an object-oriented way, which allows to execute queries and return the results as business objects, which can map the query results between the columns of the data table and the properties of the business objects.
support Contains support classes from the core and object packages, such as the SQLException class that provides exception conversion functionality.

        As can be seen from the above table, Spring's operations on the database are encapsulated in these packages, and if you want to use Spring JDBC, you need to configure it.

配置数据源
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>property name="username" value="root"/>
<property name="password" value="root"/>
<bean>
配置JDBC模板
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>注入数据源
</bean>
<bean id="xxx" class="Xxx">配置需要实例化的Bean
<properame="jdbcTemplate" ref="jdbcTemplate"/>注入JDBC模板
</bean>

        The description of the 4 properties in the above example dataSource configuration is shown in the following table:

property name meaning
driverClassName The driver name used corresponds to the Driver class in the driver JAR package.
url The address of the data source.
username Username to access the database.
password password to access the database

Method description

In the core class of JdbcTemplate, a large number of methods for updating and querying the database are provided, and we use these methods to operate the database.

method illustrate
execute() The execute(String sql) method can be used to execute sql statements
update() update() is used to perform insert, update and delete operations
query() update() is used to perform data query operations

                                                        ✨✨✨I am the dividing line✨✨✨

jdbc combat operation

        1. Create a package

         2. Create applicationContext.xml under src

<?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.cj.jdbc.Driver" />
		<!--连接数据库的url -->
		<property name="url"
			value="jdbc:mysql://localhost:3306/spring?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT&amp;useSSL=false" />
		<!--连接数据库的用户名 -->
		<property name="username" value="root" />
		<!--连接数据库的密码 -->
		<property name="password" value="123456" />
	</bean>
	<!-- 2配置JDBC模板 -->
	<bean id="jdbcTemplate"
		class="org.springframework.jdbc.core.JdbcTemplate">
		<!-- 默认必须使用数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
</beans>

        3. Introduce the jar package in the lib directory

SSM-jar package family bucket: https://tuomasi.lanzouy.com/b02uszjch

        Password: jars

        4. Create class

package com.Example.jdbc;

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创建成功!");
	}

}

        5. Create a database

 create database spring;
mysql> create database spring;
Query OK, 1 row affected (0.02 sec)

mysql> use spring;
Database changed
mysql> show tables;
Empty set (0.02 sec)

         6. Run the program

        7. View the database

mysql> use spring;
Database changed
mysql> show tables;
+------------------+
| Tables_in_spring |
+------------------+
| account          |
+------------------+
1 row in set (0.00 sec)

mysql> desc account;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int         | NO   | PRI | NULL    | auto_increment |
| username | varchar(50) | YES  |     | NULL    |                |
| balance  | double      | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

        Note: The account data table has been created successfully.

Guess you like

Origin blog.csdn.net/m0_54925305/article/details/123149019