![]() |
VOOZH | about |
In relational databases, a Many-to-One relationship occurs when multiple records in one table are associated with a single record in another table.
For example, in a workplace scenario:
This type of relationship helps to avoid data redundancy and maintain consistency.
Syntax:
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Foreign key column")
Create a project using STS and enter project details in the New Spring Starter Project window:
Click Next to select Spring Boot version and dependencies (Spring Data JPA, MySQL Driver), then click Finish.
Go to src/main/resources open application.properties in that adding the necessary properties as below
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/schemaname
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Go to src/main/java create a package for model classes(ex : com.gfg.model) and create one package for repository (ex :com.gfg.repository). Then create two model classes under the model package
Employee.java
Address.java
Go to repository package adding the JPA repository of both model classes
EmployeeRepo.java
AddressRepo.java
Go to starter class Autowire two repository interfaces and create objects for model classes
GfgMappingProjectApplication.java
Then go to Database then check for tables.
Address Table:
select * from address;
Employee Table:
select * from employee;