Advertisement
Guest User

Spring jdbc issue

a guest
Mar 11th, 2015
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. package hello;
  2.  
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6.  
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.CommandLineRunner;
  9. import org.springframework.boot.SpringApplication;
  10. import org.springframework.boot.autoconfigure.SpringBootApplication;
  11. import org.springframework.jdbc.core.JdbcTemplate;
  12. import org.springframework.jdbc.core.RowMapper;
  13.  
  14. @SpringBootApplication
  15. public class Application implements CommandLineRunner {
  16.  
  17.     public static void main(String args[]) {
  18.         SpringApplication.run(Application.class, args);
  19.     }
  20.  
  21.     @Autowired
  22.     JdbcTemplate jdbcTemplate;
  23.  
  24.     @Override
  25.     public void run(String... strings) throws Exception {
  26.     /*
  27.         System.out.println("Creating tables");
  28.         jdbcTemplate.execute("drop table customers if exists");
  29.         jdbcTemplate.execute("create table customers(" +
  30.                 "id serial, first_name varchar(255), last_name varchar(255))");
  31.  
  32.         String[] fullNames = new String[]{"John Woo", "Jeff Dean", "Josh Bloch", "Josh Long"};
  33.         for (String fullname : fullNames) {
  34.             String[] name = fullname.split(" ");
  35.             System.out.printf("Inserting customer record for %s %s\n", name[0], name[1]);
  36.             jdbcTemplate.update(
  37.                     "INSERT INTO customers(first_name,last_name) values(?,?)",
  38.                     name[0], name[1]);
  39.         }
  40.     */
  41.  
  42.         System.out.println("Querying for customer records where first_name = 'Josh':");
  43.         List<Customer> results = jdbcTemplate.query(
  44.                 "select id, first_name, last_name from customers where first_name = ?", new Object[] { "Josh" },
  45.                 new RowMapper<Customer>() {
  46.                     @Override
  47.                     public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
  48.                         return new Customer(rs.getLong("id"), rs.getString("first_name"),
  49.                                 rs.getString("last_name"));
  50.                     }
  51.                 });
  52.  
  53.         for (Customer customer : results) {
  54.             System.out.println(customer);
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement