Jay Vyas
Jay Vyas

Reputation: 2712

Joining two tables Hibernate

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 Details

2) Branch

Now, For every user, there is a field for branch, and that value should be from Branch table.

I have knowledge of OneToOne in hibernate. But it inserts a new entry for users branch field in Branch table. What I want is that, when I save user details in User Table, branch details should be just a reference from Branch table for matching row.

Thank you in advance

Upvotes: 3

Views: 400

Answers (3)

ayd
ayd

Reputation: 11

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 a pojo and mapping to 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 ..)

Upvotes: 1

KayV
KayV

Reputation: 13835

You can use the User-Branch relationship by controlling the association through its Foreign Key.

And inside the User class, you will specify the OneToOne mapping as follows:

@OneToOne
@JoinColumn(name="User_Branch_ID")
private Branch branch;

And this "User_Branch_ID" refers to the foreign key which you have created while creating the User database table as follows:

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)
);

Upvotes: 1

Radu Dumbrăveanu
Radu Dumbrăveanu

Reputation: 1416

Suppose your branches can be identified by their names:

UserDetails user = new UserDetails();
...
user.setBranch(branchRepository.findOneByName());
...
userDetailsRepository.save(user);

Having:

@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> { 
  ...
}

Upvotes: 2

Related Questions