Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JdbcTemplate in Spring Framework

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to use JdbcTemplate in the Spring framework, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Overview of JdbcTemplate

In the previous Javaweb study, you learned to manually encapsulate JdbcTemplate, which has the advantage of templated programming through (sql statements + parameters). The real JdbcTemplate class is written for us by the Spring framework. It is an object provided in the Spring framework and is a simple encapsulation of the original Jdbc API object. In addition to the JdbcTemplate,spring framework, we also provide a lot of operation template classes.

Manipulating relational data: JdbcTemplate and HibernateTemplate.

Operating on the nosql database: RedisTemplate.

Operating on message queues: JmsTemplate.

The JdbcTemplate of the Spring framework is in the jar package of spring-jdbc, in addition to importing this jar package

In addition, you also need to import a jar package for spring-tx (which is transaction-related). Of course, the jar package of connection pooling should not be forgotten that c3p0 is used here.

To use JdbcTemplate, be sure to import the three jar of Spring's database module:

You can use JdbcTemplate to quickly operate the database. This article demonstrates JdbcTemplate. The database table used in this article is employee in jdbctemplate, and the contents of the table are as follows.

Step-by-step demonstration of JdbcTemplate 1: test the data source

Database configuration file

The jdbctemplate database has been created in the local database.

Jdbc.user=rootjdbc.password=Hudiejdbc.jdbcUrl=jdbc:mysql://localhost:3306/jdbctemplatejdbc.driverClass=com.mysql.jdbc.Driver

Xml profile

Test to get a connection

Public class txTest {ApplicationContext ioc = new ClassPathXmlApplicationContext ("ApplicationContext.xml"); @ Test public void test () throws SQLException {DataSource bean = ioc.getBean (DataSource.class); Connection connection = bean.getConnection (); System.out.println (connection); connection.close ();}}

The test was performed and the connection was successfully obtained.

2: configure a JdbcTemplate for the IoC container

If you code to get a JdbcTemplate object, you can use new JdbcTemplate (dataSource); but because this object is often used, it is more appropriate to put it in an IoC container.

The specific configuration is as follows:

test

Public class txTest {ApplicationContext ioc = new ClassPathXmlApplicationContext ("ApplicationContext.xml"); JdbcTemplate jdbcTemplate= ioc.getBean (JdbcTemplate.class); @ Test public void test2 () {System.out.println (jdbcTemplate);}}

The JdbcTemplate object was printed successfully.

3: update

Change the record salary field of emp_id=5 to 1300.00

JdbcTemplate.updat (): means to update a record.

@ Test public void test3 () {String sql = "update employee set salary =? where emp_id=?;"; int update = jdbcTemplate.update (sql, 1300.00, 5); System.out.println ("Update employee table, affect" + update + "rows");}

4: bulk insert

JdbcTemplate.batchUpdate (sql, batchArgs): indicates that inserts are carried out in batches, inserting a list collection, and returns the number of rows affected.

@ Test public void test4 () {String sql = "insert into employee (emp_name,salary) values"; List batchArgs = new ArrayList (); batchArgs.add (new Object [] {"Zhang San", 998.98}); batchArgs.add (new Object [] {"Li Si", 998.98}) BatchArgs.add (new Object [] {"Wang Wu", 998.98}); batchArgs.add (new Object [] {"Zhao Liu", 998.98}); / / the length of List is the number of sql statements executed int [] is = jdbcTemplate.batchUpdate (sql, batchArgs) For (int I: is) {System.out.println (I);}}

Int [] is = jdbcTemplate.batchUpdate (sql, batchArgs); the result returned is the number of rows affected.

5: query the record of emp_id=5 and return it as a Java object.

Create JavaBean

Package com.gql.bean;public class Employee {private Integer empId; private String empName; private Double salary; / / omit the setter, getter, and toString methods. }

Query and encapsulate a single record

@ Test public void test5 () {String sql = "select emp_id empId,emp_name empName,salary from employee where emp_id=?"; / / rowMapper: specifies how the attributes of each row of records and JavaBean map Employee employee = jdbcTemplate.queryForObject (sql, new BeanPropertyRowMapper (Employee.class), 5); System.out.println (employee);}

6: query records with salary > 4000, encapsulated as List collection, return @ Test public void test6 () {String sql = "select emp_id empId,emp_name empName,salary from employee where salary >?"; List list = jdbcTemplate.query (sql, new BeanPropertyRowMapper (Employee.class), 4000); for (Employee employee: list) {System.out.println (employee) }}

Successfully encapsulated the record of salary > 400into the list collection.

7: query the largest salary

Use the max function of mysql to get the maximum salary, call the queryForObject method, and return the Double type.

@ Test public void test7 () {String sql = "select max (salary) from employee"; Double object = jdbcTemplate.queryForObject (sql, Double.class); System.out.println ("maximum wage is:" + object);}

8: use the named parameter SQL to insert an employee record and pass in the parameter value as Map.

NamedParameterJdbcTemplate is used in Spring to perform operations with a named SQL.

Add namedParameterJdbcTemplate to the IoC container.

Pass in parameter values as Map in the test.

Public class txTest {ApplicationContext ioc = new ClassPathXmlApplicationContext ("ApplicationContext.xml"); JdbcTemplate jdbcTemplate = ioc.getBean (JdbcTemplate.class); NamedParameterJdbcTemplate namedJdbcTemplate = ioc.getBean (NamedParameterJdbcTemplate.class); @ Test public void test9 () {String sql = "insert into employee (emp_name,salary) values (: empName,:salary)"; Map paramMap = new HashMap () / / put the values of all named parameters in map paramMap.put ("empName", "Xiao Hong"); paramMap.put ("salary", 12000.00); int update = namedJdbcTemplate.update (sql, paramMap); System.out.println (update) }} 9: insert an employee record using the named parameter SQL and pass in the parameter value as SqlparamSource.

Similar to the previous experiment, only different parameter types are selected.

@ Test public void test10 () {String sql = "insert into employee (emp_name,salary) values (: empName,:salary)"; Employee employee = new Employee (); employee.setEmpName ("Little Blue"); employee.setSalary (9999.00); int I = namedJdbcTemplate.update (sql, new BeanPropertySqlParameterSource (employee)) System.out.println (I);} these are all the contents of the article "how to use JdbcTemplate in Spring Framework". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report