Concatenating two Hibernate tables
I am working with Spring MVC + Hibernate (Spring data jpa).
Here I am not getting how to create a table in Hibernate for the following scenario.
I have two tables:
1) User information
2) Branch
Now there is a branch field for each user , and this value should be from the Branch table .
I have knowledge of OneToOne in sleep mode. But it does insert a new record for the users branch field in the Branch table. I want that when I save the user data in the User table , the branch data should be just a link from the Branch table to map the row.
Thank you in advance
source to share
Let's assume your branches can be identified by their names:
UserDetails user = new UserDetails();
...
user.setBranch(branchRepository.findOneByName());
...
userDetailsRepository.save(user);
Availability:
@Entity
public class UserDetails {
@Id
@GeneratedValue
Long id;
@ManyToOne
Branch branch;
...
}
@Entity
public class Branch {
@Id
@GeneratedValue
Long id;
...
}
public interface BranchRepository extends Repository<Branch, Long> {
...
}
public interface UserDetailsRepository extends Repository<UserDetails, Long> {
...
}
source to share
You can leverage User-Branch relationships by managing the association through your foreign key.
And inside the User class, you will specify the OneToOne mapping like this:
@OneToOne
@JoinColumn(name="User_Branch_ID")
private Branch branch;
And this "User_Branch_ID" refers to the foreign key that you created when you created the user database table like this:
create table BRANCH (
branch_id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
city VARCHAR(30) NOT NULL,
country VARCHAR(30) NOT NULL,
PRIMARY KEY (address_id)
);
create table USER (
user_id BIGINT NOT NULL AUTO_INCREMENT,
user_branch_id BIGINT NOT NULL,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
PRIMARY KEY (user_id),
CONSTRAINT user_branch FOREIGN KEY (user_branch_id) REFERENCES BRANCH ( branch_id)
);
source to share
step 1: create a view
create view v_BRANCH_USER as
select
a.branch_id, a.name , a.city, a.country
b.user_id,b.first_name, b.last_name
from BRANCH a, USER b
where a.branch_id = b.user_branch_id
step 2: create pojo and hibernate as a table
@Entity
@Table(name = "v_BRANCH_USER")
public class VBranchUser
String userId;
....
}
Step 3: You can query it as a table (Criteria, HQL ..)
source to share