Use RowMapper in JdbcTemplate in spring

Source: Internet
Author: User

Use RowMapper in JdbcTemplate in spring Blog Category:
    • Spring
Java code
  1. Package Com.cxl.demo.dao;
  2. Import Java.sql.ResultSet;
  3. Import java.sql.SQLException;
  4. Import java.util.List;
  5. Import Org.springframework.jdbc.core.JdbcTemplate;
  6. Import Org.springframework.jdbc.core.RowMapper;
  7. Import Com.cxl.demo.entity.User;
  8. Public class Userdaoimpl {
  9. private JdbcTemplate JdbcTemplate;
  10. public void Setjdbctemplate (JdbcTemplate jdbctemplate) {
  11. this.jdbctemplate = JdbcTemplate;
  12. }
  13. Public list<user> Getuserbyname (String username) {
  14. String sql = "SELECT * from t_user where username =?";
  15. object[] params = new object[] {username};
  16. list<user> users = null;
  17. /** 
  18. * Using the interface implementation class
  19. */
  20. Users = jdbctemplate.query (sql, params, new Userrowmapper ());
  21. /** 
  22. * Use anonymous inner class
  23. * If the Userrowmapper class is used only once, creating a separate class for it is redundant, you can use the anonymous class
  24. * Omitted to write an implementation class
  25. */
  26. Users = jdbctemplate.query (sql, params,
  27. New Rowmapper<user> () {
  28. @Override
  29. Public User Maprow (ResultSet rs, int rowNum) throws SQLException {
  30. User user = new user ();
  31. User.setid (Rs.getint ("id"));
  32. User.setusername (rs.getstring ("username"));
  33. User.setpassword (rs.getstring ("password"));
  34. return user;
  35. }
  36. });
  37. return (users ! = null && users.size () > 0)? users: null;
  38. }
  39. public class Userrowmapper implements rowmapper<user> {
  40. @Override
  41. Public User Maprow (ResultSet rs, int rowNum) throws SQLException {
  42. User user = new user ();
  43. User.setid (Rs.getint ("id"));
  44. User.setusername (rs.getstring ("username"));
  45. User.setpassword (rs.getstring ("password"));
  46. return user;
  47. }
  48. }
  49. }

Use RowMapper in JdbcTemplate in spring

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.