Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Saving an object


In this recipe, we will create a DAO method to save an object in the database; a row will be added to the corresponding database table, for example:

Getting ready

You need to have a model class, for example:

public class User {
  private Long id;
  private String firstName;
  private Integer age;

You need to have a matching database table, for example:

CREATE TABLE `user` (
  `id` int(11) AUTO_INCREMENT,
  `first_name` text,
  `age` int(11),
  PRIMARY KEY (`id`)
)

You need to have a DAO class with a JdbcTemplate attribute (Refer to the Creating a DAO class recipe)

How to do it…

Define an SQL insert query with question marks as placeholders for the actual row values. Use the update() method to execute the query using the actual values from the object:

public void add(User user) {
  String sql = "insert into user (first_name, age) values (?, ?)";
  jdbcTemplate.update(sql, user.getFirstName(), user.getAge());
}

How it works…

The jdbcTemplate object takes care of the JDBC boilerplate...