Home Spring Boot Spring Data JDBC - One to One Example

Spring Data JDBC – One to One Example

A basic quick Spring Data JDBC example on how to map One to One database tables relation in entities.

1. Project Configuration

1.1. Used Technologies :

  1. Spring Boot 2.3.0.RELEASE
  2. Spring Data JDBC 2.0.0.RELEASE
  3. Spring Framework 5.2.6.RELEASE
  4. H2 / MySql DB
  5. Lombok 1.18.12
  6. JUnit 5

1.2. Maven Dependencies :

To start working with Spring Boot with Spring Data JDBC you need dependency spring-boot-starter-data-jdbc. Use Lombok to avoid boiler plate code. Here is complete dependency list used in the example application.

        <dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

1.3. Database Tables :

Here are the database tables USER and USER_CREDENTIALS, User is associated with User_Credentials and each user have only one credential.

CREATE TABLE `USER` (
    `ID` int(11) NOT NULL AUTO_INCREMENT,
    `CREATED_TIME` datetime NOT NULL,
    `UPDATED_TIME` datetime DEFAULT NULL,
    `USER_TYPE` varchar(45) NOT NULL,
    `DOB` date NOT NULL,
    `CREDS_ID` NULL,
    PRIMARY KEY (`ID`),
    CONSTRAINT `CREDS_ID_FK` 
     FOREIGN KEY (`CREDS_ID`) REFERENCES `USER_CREDENTIALS` (`CREDS_ID`)
);

CREATE TABLE `USER_CREDENTIALS` (
  `CREDS_ID` INT NOT NULL AUTO_INCREMENT,
  `USER_NAME` VARCHAR(20) NOT NULL,
  `PASSWORD` VARCHAR(45) NOT NULL,
   UNIQUE KEY `USERNAME_UNIQUE` (`USER_NAME`),
   PRIMARY KEY (`CREDS_ID`)
);

2. One-to-One Mapping in Spring Data JDBC

Since Spring Data JDBC 1.1 supports annotation based configuration for entity relationships using Spring Data JDBC, @MappedCollection annotation can be used to map One-to-One association in entities. Let’s have look into following entity mapping for USER and USER_CREDENTIALS tables.

2.1. Credentials Entity :

@Table("USER_CREDENTIALS")
@Data // lombok
public class Credentials {

	@Id
	private Long credsId;
	private String userName;
	private String password;

}

2.2. User Entity :

@Data
public class User {

	@Id
	private Long id;
	private Date createdTime;
	private Date updatedTime;
	@Column("DOB")
	private Date dateofBirth;
	private UserType userType;

	@MappedCollection(idColumn = "CREDS_ID")
	private Credentials credentials;

}

3. Test the mapping

3.1. A test Repository

@Repository
public interface UserOneToOneTestRepository extends CrudRepository<User, Long>{

}

3.2. Test Case for Test the mapping

@SpringBootTest
public class OneToOneMappingTest {

	@Autowired
	private UserOneToOneTestRepository userTestRepository;

	@Test
	@DisplayName("One-to-One Mapping Test")
	@Sql(scripts = "/one-to-one-mapping.sql")
	void embeddedMappingTest() {

		Credentials credentials = new Credentials();
		credentials.setUserName("peterm");
		credentials.setPassword("password");

		User user = new User();
		user.setCreatedTime(new Date());
		user.setDateofBirth(new Date());
		user.setUserType(UserType.EMPLOYEE);
		user.setCredentials(credentials);

		User createdUser = userTestRepository.save(user);
		System.err.println(createdUser);
		Assert.assertTrue(createdUser != null);
	}

}

4. Conclusion

We demonstrate a Spring Data JDBC example on how to map One to One database tables relation in entities.

5. References

  1. Spring Documentation
  2. Lombok Data
  3. Hibernate One-to-One Unidirectional
  4. Spring Boot Data JDBC Example
  5. Spring Boot H2 Example
Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories