Introduction to Spring's use of JDBCTemplate, springjdbctemplate
Spring provides a powerful template class called jdbcTemplate to simplify JDBC operations. Both the DataSource object and the jdbcTemplate object of the data source can be defined in the configuration file in the form of beans, fully exert the power of de
Use RowMapper in JdbcTemplate in springBlog Category:
Spring
Java code
Package Com.cxl.demo.dao;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.util.List;
Import Org.springframework.jdbc.core.JdbcTemplate;
Import Org.springframework.jdbc.core.RowMapper;
Import Com.cxl.demo.entity.User;
Public class Userdaoimpl {
private
Tags: spring-using configuration files to complete JdbcTemplate operations databaseFirst, create a spring projectProject Name: spring101302Ii. adding a jar package to the project1. Create a Lib directory in your project/lib2. Add spring support under the Lib directoryCommons-logging.jarJunit-4.10.jarLog4j.jarMysql-conn
/sw_database "); //datasource.setuser ("root");//Datasource.setpassword ("root");
String SQL= "INSERT into Sw_user (Username,password) VALUES (?,?)"; intCount=jdbctemplate.update (SQL, "Bullet", "battle-Man song"); if(count==1) {
return true; }
return false; }
} To use the JdbcTemplate object in Userdao, this object is also injected through the config file XML, which needs to be setjdbctemplate () to match The
corresponding object * Note that it is not called queryforobject (String sql, Class*/
Public voidTestqueryforobject () {String SQL= "Select Id,last_name lastname,email,dept_id as \" department.id\ "from tables where id=?"; RowMapperNewBeanpropertyrowmapperclass); Employee Employee=jdbctemplate.queryforobject (SQL, rowmapper,1);
SYSTEM.OUT.PRINTLN (employee); }
//Perform batch update: Batch INSERT, update, DELETE//the last parameter is the List type of object[]: Because modifyi
The Spring framework performs crud operations on the jdbcTemplate of the dao layer, namely, update operations on the database and jdbctemplatecrud operations.
Use jdbcTemplate
The principle is to load the Driver Class. forName ("com. mysql. jdbc. Driver ");
And Connection conn = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/sw_database? User = ro
Filesystemxmlapplicationcontext (
"
Src/database_config.xml
"
);
//
E:/demoworkspace/spring is the main directory of the project.
Jdbctemplate JT = New Jdbctemplate (datasource) Context. Getbean ( " Oracledatasourcetest " )); // Test Method Object [] Arg = New Object [] { 10 };List list = (Arraylist) JT. Query ( " Select *
classes//Note that the call is not a queryForList methodPublicvoidTestqueryforlist () {String sql= "select Id,last_name,email from tables where id>?"; RowmapperNew BeanpropertyrowmapperClass); List); SYSTEM.OUT.PRINTLN (employees); }/*** Get a record from the database, actually get a corresponding object * Note that it is not called queryforobject (String sql, class*/PublicvoidTestqueryforobject () {String sql= "select Id,last_name lastname,email,dept_id as \" department.id\ "from tables where
Summary:Put the spring jar package into the Lib directory, the Jar can be based on the function you want to choose, if lazy or do not want to use the function later put together, pay attention to not put the document jar and source jarSuddenly think of spring's requirements for the environment, also forget to say that my JDK version is 1.6, the database will use MySQL, Application server is Tomcat7.0First go to sp
/schema/context/spring-context.xsd " >Iv. Testing1. Create the test directory on the project/test2. Creating a test package under the test directoryPackage Name: Cn.jbit.spring101301.test3. Create a test class under a test packageTest class Name: Jdbctemplatedemo.javaTest the contents of the class:public class Jdbctemplatedemo {/*** Add data using spring JdbcTemplate
In daily development, we often need to access the database, which inevitably need to deal with resultset. Spring JdbcTemplate wraps the native JDBC API, allowing programmers to focus more on business logic coding, such as querying database operations:
Public User Queryuserbyid (long id) {
return Jdbctemplate.queryforobject ("select * from Tb_employee WHERE id=?", New Ob Ject[]{id}, new Rowmapper
W
() + "," +book.getbooktype ());}}}Careful you, you will find a series of methods in JdbcTemplate examples, such as: Queryforxxx,update,delete greatly simplifies the JDBC operation.Of course, it can be further optimized, that is, through dependency injection, directly inject jdbctemplate into the DAO class's JDBCT field.First look at the new applicationcontext.xml configuration file:Xmlns:xsi= "Http://www.w
The jdbcTemplate operations of the Spring framework for the dao layer include crud and jdbctemplatecrud.
Crud refers to the basic operations on the database or persistent layer, including
Create, Retrieve, Update, and Delete)
Spring not only encapsulates JDBC, but also Hibernate, and Ibatis
JdbcTemplate is similar to
Spring MVC Article 2. Using JdbcTemplate for database operations, mvcjdbctemplate
The previous article was just a simple Spring MVC framework, and then added some interactions with the database.
1. Add jdbc configurationsAfter adding relevant dependencies to maven, configure database access parameters and data sources. Use the configuration file for database para
JdbcTemplate JdbcTemplate; public static void Main (string[] args) {springapplication springapplication = new Springapplication (APPLICATIONMAIN.CLA
SS);
Springapplication.run (args); } @Override public void Run (string ... args) throws Exception {string querymerchandiseinfosql = "Select Id,worth,chan
nel_id,template_id from Merchandise_info "; list At this point a simple springboot+
and consume resources
//Note the order of closing, the last used first close
if(Result! =NULL) Result.close ();if(Pre! =NULL) Pre.close ();if(Con! =NULL) Con.close (); System.out.println ("The database connection is closed! "); }Catch(Exception e)
{E.printstacktrace (); }
}
}/** * Test SQL injection attacks.
JdbcTemplate This security issue does not exist. * @param ID * @return * *
Pub
Spring JdbcTemplate is a lightweight ORM framework that makes it much easier to replace the native JDBC operations database with it.
This article introduces a helper class (JdbcTemplate) for JDBC in spring, which encapsulates the operation of JDBC and is very convenient to use. maven Dependency
Model
Employee table:
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.