Spring integrates JDBC to implement simple addition, deletion, modification, and continuation-to implement query based on RowMaper and jdbcrowmaper

Source: Internet
Author: User

Spring integrates JDBC to implement simple addition, deletion, modification, and continuation-to implement query based on RowMaper and jdbcrowmaper

Spring integrates JDBC to implement simple addition, deletion, modification, and continuation-to implement query based on RowMaper:

In the previous article, Spring integrates JDBC to implement simple addition, deletion, and modification, and then queries the database.

First, check the Spring documentation. For Spring documentation and image downloads, see Spring simple learning plan, which contains a simple learning plan!



Based on the preceding documents, compile the query method. The sample code is as follows:

Package org. oms. spring. dao; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. iterator; import java. util. list; import javax. annotation. resource; import javax. SQL. dataSource; import org. oms. spring. model. group; import org. oms. spring. model. user; import org. springframework. jdbc. core. jdbcTemplate; import org. springframework. jdbc. core. rowMapper; import org. springframework. stereotype. reposito Ry; @ Repository ("userJdbcDao") public class UserDao implements IUserDao {private JdbcTemplate;/*** Set the JDBC DataSource to obtain connections from. * // @ Resourcepublic void setDataSource (DataSource dataSource) {JdbcTemplate = new JdbcTemplate (dataSource) ;}@ Overridepublic void add (User user, int gid) {JdbcTemplate. update ("insert into user (username, password, gid, age, birthday, createdate) Value (?,?,?,?,?,?) ", User. getUsername (), user. getPassword (), gid, user. getAge (), user. getBirthDay (), user. getCreateDate () ;}@ Overridepublic void update (User user User, int gid) {JdbcTemplate. update ("update user set username = ?, Password = ?, Gid = ?, Age = ?, Birthday = ?, Createdate =? Where id =? ", User. getUsername (), user. getPassword (), gid, user. getAge (), user. getBirthDay (), user. getCreateDate (), user. getId () ;}@ Overridepublic void delete (int id) {JdbcTemplate. update ("delete from user where id =? ", Id) ;}@ Overridepublic User load (int id) {String SQL =" select t1.id uid, t1 .*, t2. * from user t1 left join 'group' t2 on (t1.gid = t2.id) where t1.id =? ";/*** The first parameter is the SQL statement * The second parameter is the parameter value in the SQL statement. You need to input an object array * The third parameter is a RowMapper, this RowMapper can correspond an object to a database field. To implement this RowMapper, You need to implement the mapRow method. * This mapRow method contains the rs parameter, rs can be used to effectively obtain database fields. * If this method is used repeatedly in DAO, it is recommended to use internal classes, instead of using an anonymous internal class */User u = (User) JdbcTemplate. queryForObject (SQL, new Object [] {id}, new RowMapper <User> () {@ Overridepublic User mapRow (ResultSet rs, int rowNum) throws SQLException {Group group = new Group (); group. set Name (rs. getString ("name"); group. setId (rs. getInt ("gid"); User user = new User (); user. setGroup (group); user. setId (rs. getInt ("uid"); user. setUsername (rs. getString ("username"); user. setPassword (rs. getString ("password"); user. setAge (rs. getInt ("age"); user. setBirthDay (rs. getDate ("birthday"); user. setCreateDate (rs. getDate ("createdate"); return user ;}}); return u ;}/ *** the preceding method is simplified * @ param id * @ return */public User loadOther (int id) {String SQL = "select t1.id uid, t1. *, t2. * from user t1 left join 'group' t2 on (t1.gid = t2.id) where t1.id =? "; User u = (User) JdbcTemplate. queryForObject (SQL, new Object [] {id}, new UserMapper (); return u ;}@ Overridepublic List <User> list (String SQL, Object [] args) {// query the total number of entries. Obtain the integer String sqlCount = "select count (1) from user"; int count = JdbcTemplate. queryForInt (sqlCount); System. out. println (count); // query a single column to obtain the String type List String sqlCol = "select username from user"; List <String> cols = JdbcTemplate. queryForList (sqlCol, String. class); for (int I = 0; I <cols. size (); I ++) {System. out. println (cols. get (I);} // query multiple columns of String sqlCols = "select username, password from user"; List <User> users = JdbcTemplate. query (sqlCols, new RowMapper <User> () {@ Overridepublic User mapRow (ResultSet rs, int rowNum) throws SQLException {User user = new User (); user. setUsername (rs. getString ("username"); user. setPassword (rs. getString ("password"); return user ;}}); for (int I = 0; I <users. size (); I ++) {System. out. println (users. get (I ). toString ();} // returns JdbcTemplate to the query list. query (SQL, args, new UserMapper ();}/*** it is recommended to use internal classes to solve the problem, instead of using an anonymous internal class * @ author sunlight **/private class UserMapper implements RowMapper <User >{@ Overridepublic User mapRow (ResultSet rs, int rowNum) throws SQLException {Group group = new Group (); group. setName (rs. getString ("name"); group. setId (rs. getInt ("gid"); User user = new User (); user. setGroup (group); user. setId (rs. getInt ("uid"); user. setUsername (rs. getString ("username"); user. setPassword (rs. getString ("password"); user. setAge (rs. getInt ("age"); user. setBirthDay (rs. getDate ("birthday"); user. setCreateDate (rs. getDate ("createdate"); return user ;}}}

This part of content is frequently encountered in queries, So I directly added it to the query list method:

// Query the total number of items and obtain the integer String sqlCount = "select count (1) from user"; int count = JdbcTemplate. queryForInt (sqlCount); System. out. println (count); // query a single column to obtain the String type List String sqlCol = "select username from user"; List <String> cols = JdbcTemplate. queryForList (sqlCol, String. class); for (int I = 0; I <cols. size (); I ++) {System. out. println (cols. get (I);} // query multiple columns of String sqlCols = "select username, password from user"; List <User> users = JdbcTemplate. query (sqlCols, new RowMapper <User> () {@ Overridepublic User mapRow (ResultSet rs, int rowNum) throws SQLException {User user = new User (); user. setUsername (rs. getString ("username"); user. setPassword (rs. getString ("password"); return user ;}}); for (int I = 0; I <users. size (); I ++) {System. out. println (users. get (I ). toString ());}

Test code:
Package org. oms. spring. test; import static org. junit. assert. *; import java. util. date; import java. util. list; import javax. annotation. resource; import org. junit. test; import org. junit. runner. runWith; import org. oms. spring. dao. IGroupDao; import org. oms. spring. dao. IUserDao; import org. oms. spring. model. group; import org. oms. spring. model. user; import org. springframework. test. context. contextConfiguration; import org. springframework. test. context. junit4.SpringJUnit4ClassRunner;/*** after the following annotations are used, you can directly inject the dependency into the Test ** @ author sunlight ** // run Junit in the Spring testing environment @ RunWith (SpringJUnit4ClassRunner. class) // load beans. xml file @ ContextConfiguration ("/beans. xml ") public class TestJdbc {@ Resource (name =" userJdbcDao ") private IUserDao userJdbcDao; @ Resource (name =" groupJdbcDao ") private IGroupDao groupJdbcDao; @ Testpublic void testAdd () {Group group = new Group ("test1"); groupJdbcDao. add (group); System. out. println (group. getId (); User user = new User ("I am Spring", "123", 20, new Date (), new Date (); userJdbcDao. add (user, group. getId () ;}@ Testpublic void testUpdate () {User user = new User ("Spring", "123", 20, new Date (), new Date ()); user. setId (2); userJdbcDao. update (user, 1) ;}@ Testpublic void testDel () {userJdbcDao. delete (2) ;}@ Testpublic void testLoad () {User user = userJdbcDao. load (1); System. out. println (user) ;}@ Testpublic void testList () {String SQL = "select t1.id uid, t1 .*, t2. * from user t1 left join 'group' t2 on (t1.gid = t2.id) "; List <User> users = userJdbcDao. list (SQL, null); for (int I = 0; I <users. size (); I ++) {System. out. println (users. get (I ). toString ());}}}

Test results:


The above is the addition, deletion, and Modification Operation implemented by JdbcTemplate (that is, the parameter has "?"), The following documents use NamedParameterJdbcTemplate. This method will be implemented later!







The above is a simple addition, deletion, and modification operation of JDBC. The template design mode is used to implement this function in the next section!

If you need to reprint it, please indicate the source!



Kneeling, JDBC (MySQL) works with Spring's add, delete, modify, and query examples to directly import the project to Myeclipse for running.

Please refer to this article for details.
Reference: www.cnblogs.com/..c.html

How does JAVA implement JDBC addition, deletion, modification, and query?

JAVA uses JDBC to perform database operations in less than one sentence. I have read a book called JAVA Network Programming details, which details JAVA database operations, sun weiqin, the author of JDBC operations, is very detailed and thorough. You can go to the bookstore to see them. After reading them, you can learn them with your own practices.

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.