Embedded Entity in Spring Data JDBC

Overview

In Spring Data JDBC, embedded entities allow for the inclusion of one entity's fields within another entity's table. This is achieved using the @Embedded annotation. This annotation can also specify behavior for empty embedded fields, such as using null when the fields are not populated. This feature is particularly useful for simplifying database schemas by reducing the number of tables and relationships needed to represent complex data structures.

Implementation

Java Class Example

The following Java class demonstrates how to use the @Embedded annotation in a Spring Data JDBC application. In this example, the User class contains an embedded Address entity. The @Embedded annotation is used to specify that the Address fields should be included in the USERS table. Additionally, the onEmpty attribute is set to Embedded.OnEmpty.USE_NULL, indicating that if the embedded fields are empty, the address field should be set to null.

@Table("USERS")
public class User {

    @Id
    private Long id;

    // . . .

    @Embedded(onEmpty = Embedded.OnEmpty.USE_NULL)
    private Address address;
}

SQL Schema

The SQL schema for the USERS table is automatically generated to include the fields of the embedded Address entity. The following SQL script shows the creation of the USERS table, which includes columns for the Address fields (STREET and CITY).

Listing 15.20 The schema.sql file for embedded entities

Path: Ch15/spring-data-jdbc4/src/main/resources/schema.sql

DROP TABLE IF EXISTS USERS;

CREATE TABLE USERS (
   ID INTEGER AUTO_INCREMENT PRIMARY KEY,
   ACTIVE BOOLEAN,
   USERNAME VARCHAR(30),
   EMAIL VARCHAR(30),
   LEVEL INTEGER,
   REGISTRATION_DATE DATE,
   STREET VARCHAR(30) NOT NULL,
   CITY VARCHAR(20) NOT NULL
);

In this schema, the STREET and CITY columns are part of the USERS table, representing the embedded Address entity. If these columns are empty, the address field in the User class will be null, as specified by the @Embedded annotation configuration.