Close

Spring - Inserting data using SimpleJdbcInsert

[Last Updated: Sep 15, 2017]

SimpleJdbcInsert wraps JdbcTemplate to simplify the code needed to construct a basic insert statement.

Example

Using SimpleJdbcInsert

@Repository
public class PersonDao implements Dao<Person> {
  @Autowired
  private DataSource dataSource;
  private JdbcTemplate jdbcTemplate;
  private SimpleJdbcInsert jdbcInsert;

  @PostConstruct
  private void postConstruct() {
      jdbcTemplate = new JdbcTemplate(dataSource);
      jdbcInsert = new SimpleJdbcInsert(dataSource)
              .withTableName("PERSON").usingGeneratedKeyColumns("ID");
  }

  @Override
  public void save(Person person) {
      SqlParameterSource parameters = new BeanPropertySqlParameterSource(person);
      jdbcInsert.execute(parameters);
  }
    .............
  @Override
  public List<Person> loadAll() {
      return jdbcTemplate.query("select * from Person", (resultSet, i) -> {
          return toPerson(resultSet);
      });
  }

  private Person toPerson(ResultSet resultSet) throws SQLException {
      Person person = new Person();
      person.setId(resultSet.getLong("ID"));
      person.setFirstName(resultSet.getString("FIRST_NAME"));
      person.setLastName(resultSet.getString("LAST_NAME"));
      person.setAddress(resultSet.getString("ADDRESS"));
      return person;
  }
}
public class Person {
  private long id;
  private String firstName;
  private String lastName;
  private String address;
    .............
}

src/main/resources/createPersonTable.sql

CREATE TABLE PERSON(
ID BIGINT  PRIMARY KEY AUTO_INCREMENT,
FIRST_NAME VARCHAR(255),
LAST_NAME VARCHAR(255),
ADDRESS VARCHAR(255)
);

A client bean

@Component
public class PersonClient {

  @Autowired
  Dao<Person> personDao;

  public void process() {
      Person person = Person.create("Dana", "Whitley", "464 Gorsuch Drive");
      System.out.println("saving: "+person);
      personDao.save(person);

      person = Person.create("Robin", "Cash", "64 Zella Park");
      System.out.println("saving: "+person);
      personDao.save(person);

      List<Person> list = personDao.loadAll();
      System.out.println("Loaded all: " + list);

  }
}

Java Config

@Configuration
@ComponentScan
public class AppConfig {

  @Bean
  public DataSource h2DataSource() {
      return new EmbeddedDatabaseBuilder()
              .setType(EmbeddedDatabaseType.H2)
              .addScript("createPersonTable.sql")
              .build();
  }

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      context.getBean(PersonClient.class).process();
  }
}

Output

saving: Person{id=0, firstName='Dana', lastName='Whitley', address='464 Gorsuch Drive'}
saving: Person{id=0, firstName='Robin', lastName='Cash', address='64 Zella Park'}
Loaded all: [Person{id=1, firstName='Dana', lastName='Whitley', address='464 Gorsuch Drive'}, Person{id=2, firstName='Robin', lastName='Cash', address='64 Zella Park'}]

Example Project

Dependencies and Technologies Used:

  • spring-context 4.2.3.RELEASE: Spring Context.
  • spring-jdbc 4.2.3.RELEASE: Spring JDBC.
  • h2 1.4.190: H2 Database Engine.
  • JDK 1.8
  • Maven 3.0.4

SimpleJdbcInsert Example Select All Download
  • simple-jdbc-insert
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • PersonDao.java
          • resources

    See Also