Skip to content

3.1.1 Adapting the domain for persistence

When persisting objects to a database, it’s generally a good idea to have one field that uniquely identifies the object. Your Ingredient class already has an id field, but you need to add id fields to both Taco and TacoOrder as well.

Moreover, it might be useful to know when a Taco is created and when a TacoOrder is placed. You’ll also need to add a field to each object to capture the date and time that the objects are saved. The following listing shows the new id and createdAt fields needed in the Taco class.

Listing 3.3 Adding ID and timestamp fields to the Taco class

java
@Data
public class Taco {
    
    private Long id;
    
    private Date createdAt;
    
    ...
}

Because you use Lombok to automatically generate accessor methods at run time, there’s no need to do anything more than declare the id and createdAt properties. They’ll have appropriate getter and setter methods as needed at run time. Similar changes are required in the TacoOrder class, as shown here:

java
@Data
public class TacoOrder implements Serializable {

  private static final long serialVersionUID = 1L;

  private Long id;

  private Date placedAt;  
  // ...
}

Again, Lombok automatically generates the accessor methods, so these are the only changes required in TacoOrder. If for some reason you choose not to use Lombok, you’ll need to write these methods yourself.

Your domain classes are now ready for persistence. Let’s see how to use JdbcTemplate to read and write them to a database.

Released under the MIT License.