It is a relationship between two tables where a row from one table can have multiple matching rows in another table.
For example, let’s take USERS and BANK_ACCOUNT_DETAILS tables. One user can have multiple bank accounts, but a bank account always associated with one user.
USERS table defined like below.
USER_ID
|
FIRST_NAME
|
LAST_NAME
|
BANK_ACCOUNT_DETAILS defined like below.
ACCOUNT_ID
|
ACCOUNT_NUMBER
|
ADDRESS
|
BRANCH
|
IFSC_CODE
|
MY_USER_ID
|
MY_USER_ID is a foreign key that refers to USER_ID column of USERS table.
Entities are modelled like below.
@Entity
@Table(name = "USERS")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
private int id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "MY_USER_ID")
@JsonManagedReference
private Set<BankAccount> bankAccounts;
......
......
}
@Entity
@Table(name = "BANK_ACCOUNT_DETAILS")
public class BankAccount {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ACCOUNT_ID")
private int id;
@Column(name = "ACCOUNT_NUMBER")
private String accountNumber;
@Column(name = "BRANCH")
private String branch;
@Column(name = "IFSC_CODE")
private String ifscCode;
@Column(name = "ADDRESS")
private String address;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "MY_USER_ID")
private User user;
......
......
}
Find the below working application.
package com.sample.app.entity;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
@Table(name = "USERS")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
private int id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "MY_USER_ID")
@JsonManagedReference
private Set<BankAccount> bankAccounts;
public int getId() {
return id;
}
public void setId(int 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 Set<BankAccount> getBankAccounts() {
return bankAccounts;
}
public void setBankAccounts(Set<BankAccount> bankAccounts) {
this.bankAccounts = bankAccounts;
}
}
BankAccount.java
package com.sample.app.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
@Table(name = "BANK_ACCOUNT_DETAILS")
public class BankAccount {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ACCOUNT_ID")
private int id;
@Column(name = "ACCOUNT_NUMBER")
private String accountNumber;
@Column(name = "BRANCH")
private String branch;
@Column(name = "IFSC_CODE")
private String ifscCode;
@Column(name = "ADDRESS")
private String address;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "MY_USER_ID")
private User user;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getIfscCode() {
return ifscCode;
}
public void setIfscCode(String ifscCode) {
this.ifscCode = ifscCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
BankAccountDto.java
package com.sample.app.dto;
public class BankAccountDto {
private String accountNumber;
private String branch;
private String ifscCode;
private String address;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getIfscCode() {
return ifscCode;
}
public void setIfscCode(String ifscCode) {
this.ifscCode = ifscCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
UserDto.java
package com.sample.app.dto;
import java.util.List;
public class UserDto {
private String firstName;
private String lastName;
private List<BankAccountDto> accounts;
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 List<BankAccountDto> getAccounts() {
return accounts;
}
public void setAccounts(List<BankAccountDto> accounts) {
this.accounts = accounts;
}
}
BankAccountRepository.java
package com.sample.app.repository;
import org.springframework.data.repository.CrudRepository;
import com.sample.app.entity.BankAccount;
public interface BankAccountRepository extends CrudRepository<BankAccount, Integer> {
}
UserRepository.java
package com.sample.app.repository;
import org.springframework.data.repository.CrudRepository;
import com.sample.app.entity.User;
public interface UserRepository extends CrudRepository<User, Integer> {
}
BankAccountService.java
package com.sample.app.service;
import com.sample.app.entity.BankAccount;
public interface BankAccountService {
BankAccount getAccount(int id);
}
UserService.java
package com.sample.app.service;
import com.sample.app.dto.UserDto;
import com.sample.app.entity.User;
public interface UserService {
User save(UserDto emp);
User getById(int id);
}
BankAccountServiceImpl.java
package com.sample.app.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sample.app.entity.BankAccount;
import com.sample.app.repository.BankAccountRepository;
import com.sample.app.service.BankAccountService;
@Service
public class BankAccountServiceImpl implements BankAccountService {
@Autowired
private BankAccountRepository salaryAccRepo;
@Override
public BankAccount getAccount(int id) {
return salaryAccRepo.findById(id).get();
}
}
UserServiceImpl.java
package com.sample.app.service.impl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sample.app.dto.BankAccountDto;
import com.sample.app.dto.UserDto;
import com.sample.app.entity.BankAccount;
import com.sample.app.entity.User;
import com.sample.app.repository.UserRepository;
import com.sample.app.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepo;
@Override
@Transactional
public User save(UserDto empDto) {
String firstName = empDto.getFirstName();
String lastName = empDto.getLastName();
User emp = new User();
emp.setFirstName(firstName);
emp.setLastName(lastName);
List<BankAccountDto> bankAccountsDto = empDto.getAccounts();
Set<BankAccount> accounts = new HashSet<>();
for (BankAccountDto accDto : bankAccountsDto) {
BankAccount bankAccount = new BankAccount();
bankAccount.setAccountNumber(accDto.getAccountNumber());
bankAccount.setAddress(accDto.getAddress());
bankAccount.setBranch(accDto.getBranch());
bankAccount.setIfscCode(accDto.getIfscCode());
accounts.add(bankAccount);
}
emp.setBankAccounts(accounts);
return userRepo.save(emp);
}
@Override
public User getById(int id) {
return userRepo.findById(id).get();
}
}
AccountController.java
package com.sample.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.sample.app.entity.BankAccount;
import com.sample.app.service.BankAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@Api(tags = { "This section contains all Account Speicifc Operations" })
public class AccountController {
@Autowired
private BankAccountService salaryAccService;
@ApiOperation(value = "Get Account Details", notes = "Get Account Details by id")
@GetMapping(value = "/accounts/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BankAccount> getAccount(@PathVariable final Integer id) {
BankAccount salaryAcc = salaryAccService.getAccount(id);
return new ResponseEntity<>(salaryAcc, HttpStatus.CREATED);
}
}
UserController.java
package com.sample.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.sample.app.dto.UserDto;
import com.sample.app.entity.User;
import com.sample.app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@Api(tags = { "This section contains all user Speicifc Operations" })
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value = "Create new user", notes = "Create new user")
@PostMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> saveEmployee(@RequestBody UserDto empDto) {
User persistedEmp = userService.save(empDto);
return new ResponseEntity<>(persistedEmp, HttpStatus.CREATED);
}
@ApiOperation(value = "Get user", notes = "Get user by id")
@GetMapping(value = "/users/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getEmployees(@PathVariable final Integer id) {
User persistedEmp = userService.getById(id);
return new ResponseEntity<>(persistedEmp, HttpStatus.CREATED);
}
}
SwaggerConfig.java
package com.sample.app.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Component
@EnableAutoConfiguration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().paths(PathSelectors.any())
.apis(RequestHandlerSelectors.basePackage("com.sample.app.controller")).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Query builder").description("Query builder using spring specification")
.version("2.0").build();
}
}
App.java
package com.sample.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String args[]) {
SpringApplication.run(App.class, args);
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sample.app</groupId>
<artifactId>oneToManyForeignKey</artifactId>
<version>1</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
</project>
Create application.properties file under src/main/resources folder.
application.properties
logging.level.root=WARN logging.level.org.hibernate=ERROR ## H2 specific properties spring.h2.console.enabled=true spring.h2.console.path=/h2 spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1; spring.datasource.username=krishna spring.datasource.password=password123 spring.datasource.driverClassName=org.h2.Driver ## JPA specific properties # Creates the schema, destroying previous data. spring.jpa.hibernate.ddl-auto=create spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.show-sql=true #spring.jpa.properties.hibernate.format_sql=true ## Database connection pooling properties # Number of ms to wait before throwing an exception if no connection is available. spring.datasource.max-wait=10000 # Maximum number of active connections that can be allocated from this pool at the same time. spring.datasource.tomcat.max-active=10 spring.datasource.tomcat.max-idle=5 spring.datasource.tomcat.min-idle=3 spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false
Total project structure looks like below.
Run App.java.
Open swagger url 'http://localhost:8080/swagger-ui.html' in browser to interact with the REST services.
Open the url 'http://localhost:8080/h2/login.do' to see H2 console.
You can download complete working application from this link.
No comments:
Post a Comment