Skip to content

_refactor #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 0 additions & 11 deletions jpa-one-to-one-demo/Readme.md
Original file line number Diff line number Diff line change
@@ -1,11 +0,0 @@
# Hibernate One to One Mapping Example with Spring Boot and JPA

Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-one-mapping-example/

## Setup the Application

1. Create a database named `hibernate_one_to_one_demo`.

2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation.

3. Type `mvn spring-boot:run` from the root directory of the project to run the application.
16 changes: 9 additions & 7 deletions jpa-one-to-one-demo/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>hibernate-one-to-one-demo</artifactId>
<artifactId>jpa-one-to-one-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>hibernate-one-to-one-demo</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

Expand All @@ -33,10 +31,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,59 +3,72 @@
import com.example.jpa.model.Gender;
import com.example.jpa.model.User;
import com.example.jpa.model.UserProfile;
import com.example.jpa.repository.UserRepository;
import com.example.jpa.repository.UserProfileRepository;
import com.example.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Calendar;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Date;
import java.util.List;

@SpringBootApplication
public class JpaOneToOneDemoApplication implements CommandLineRunner {
@RestController
public class JpaOneToOneDemoApplication implements ApplicationRunner {


@Autowired
private UserRepository userRepository;

@Autowired
private UserProfileRepository userProfileRepository;
private UserProfileRepository userProfileRepository;

public static void main(String[] args) {
SpringApplication.run(JpaOneToOneDemoApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
// Clean up database tables
userProfileRepository.deleteAllInBatch();
userRepository.deleteAllInBatch();

//=========================================
@GetMapping("/users")
public Collection<User> getUsers(){
return userRepository.findAll();
}

// Create a User instance
User user = new User("Rajeev", "Singh", "[email protected]",
"MY_SUPER_SECRET_PASSWORD");
@GetMapping("/user_profiles")
public Collection<UserProfile> getUserProfiles(){
return userProfileRepository.findAll();
}

Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.set(1992, 7, 21);
@Override
public void run(ApplicationArguments args) throws Exception {

// Create a UserProfile instance
UserProfile userProfile = new UserProfile("+91-8197882053", Gender.MALE, dateOfBirth.getTime(),
"747", "2nd Cross", "Golf View Road, Kodihalli", "Bangalore",
"Karnataka", "India", "560008");
UserProfile userProfile1 = new UserProfile();
userProfile1.setAddress1("Address 1");
userProfile1.setAddress2("Address 2");
userProfile1.setCity("City 1");
userProfile1.setCountry("Country 1");
userProfile1.setDateOfBirth(new Date());
userProfile1.setGender(Gender.FEMALE);


// Set child reference(userProfile) in parent entity(user)
user.setUserProfile(userProfile);
User user1 = new User();
user1.setEmail("[email protected]");
user1.setFirstName("SomeFirstName");
user1.setLastName("SomeLastName");
user1.setPassword("SomePassword");
userRepository.save(user1);

// Set parent reference(user) in child entity(userProfile)
userProfile.setUser(user);
userProfile1.setUser(user1);
userProfileRepository.save(userProfile1);

// Save Parent Reference (which will save the child as well)
userRepository.save(user);
userProfileRepository.findAll().forEach(userProfile -> {
System.out.println(userProfile.getAddress1() + " " + userProfile.getAddress2());
System.out.println(userProfile.getUser().getFirstName() + " " + userProfile.getUser().getLastName());
});

//=========================================
}


}
72 changes: 7 additions & 65 deletions jpa-one-to-one-demo/src/main/java/com/example/jpa/model/User.java
Original file line number Diff line number Diff line change
@@ -1,103 +1,45 @@
package com.example.jpa.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;

/**
* Created by rajeevkumarsingh on 20/11/17.
*/
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 65)
@Column(name = "first_name")
private String firstName;

@Size(max = 65)
@Column(name = "last_name")
private String lastName;

@NotNull
@Email
@Size(max = 100)
@Column(unique = true)
private String email;

@NotNull
@Size(max = 128)
private String password;

@OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private UserProfile userProfile;

// Hibernate requires a no-arg constructor
public User() {

}

public User(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}


public UserProfile getUserProfile() {
return userProfile;
}

public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
}
Loading