简体   繁体   中英

How to define relationship between models in Java and Database?

I have three models(namely Users, UsersImages, UserLocation) corresponding to which there are three tables in database. I have taken Users as the owner entity because the if the user is there then only its images and its location is possible and hence define this kind of relationship.

I have two doubts as:

  1. If this is the correct of thinking and making the owner entity? If so,
  2. I don't have any userId in class UserImages but the has the reference of Users class, so how do I add or update or delete the userImages based upon userId.
  3. If this is wrong, then what is the correct way of making the relationship between these three models.
class Users{
  
  long id;

  @OneToMany
  List<UserImages> userImagesList;

  @OneToOne
  UserLocation userLocation;

  // some other data members

  // getters and setters
}
class UserImages{
  
  long id;

  @ManyToOne
  Users usersObj;

  // some other data members

  // getters and setters
}
class UserLocation{
  
  long id;

  @OneToOne(mappedBy="userlocation")
  Users usersObj;

  // some other data members

  // getters and setters
}

Could anyone help me to clear this doubt??

Thanks

1. If this is the correct of thinking and making the owner entity?

Yes, your approach is correct.

2. I don't have any userId in class UserImages but the has the reference of Users class, so how do I add or update or delete the userImages based upon userId

Since you have the reference of Users in UserImages , you can get userImages by users itself. Hibernate will do that for you. If you still want to get userImages by userId , you can do so as well by users.getId() - which will give you userId

Spring-data will automatically provide you such serves methods -

public interface UserImagesRepository extends CrudRepository<UserImages, Long> {
  UserImages findById(long id);
}

Or you can manually write your own -

@Repository
Public class YourServiceClass {

    @PersistenceContext
    private EntityManager em;    

    public UserImages getUserImageByUser(Users user) {
        return em.createQuery("FROM UserImages WHERE usersObj.id = :userId")
                  .setParameter("userId", user.getId())
                  .getSingleResult();
    }
}

First of all you have to decide if you want to have unidirectional or bidirectional relationships in the ORM layer, namely hibernate. There are advantages and disadvantages between them and like always the choice varies between the usage. From what I see you would like to have bidirectional one here, so it is a crucial to provide synchronization methods (add and remove) between entities.

  1. As far as "owner entity" concerns you have to tell hibernate who is the owner of the relationship, that is who has the reference to the foreign key. You can do it either using @JoinColumn or mappedBy , in bidirectional use both.
@Entity
@Table(name = "user")
class Users {
  
  @Id
  Long id;

  @OneToMany(cascadeType = CascadeType.ALL)
  @JoinColumn(name = "user_id") // here Users is the owning side
  List<UserImages> userImagesList = new LinkedList<>();

  @OneToOne
  @JoinColumn(name = "user_id")
  UserLocation userLocation;

  void addUserImage(UserImage userImage) {
     this.userImagesList.add(userImage);
     userImage.setUser(this);
  }

  void removeUserImage(UserImage userImage) {
     this.userImagesList.remove(userImage);
     userImage.setUser(null);
  }

  // some other data members

  // getters and setters

  // hashCode and equals!!!
}
@Entity
@Table(name = "user_image")
class UserImages {
  
  @Id
  Long id;

  @ManyToOne(mappedBy = "userImagesList")
  Users usersObj;

  // some other data members

  // hashCode and equals!!!

  // getters and setters
}
  1. If your Users entity is persistent, then when you remove some image from the userImagesList it will be synchronized with the database. When the method responsible for removing that image from the list finishes (or when you make entityManager.flush() ), that image will be removed from the database, because of CascadeType . In bidirectional mapping removing should be done by your synchronization remove method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM