简体   繁体   English

如何定义Java中的模型与数据库的关系?

[英]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.我有三个模型(即Users,UsersImages,UserLocation)对应于数据库中有三个表。 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.我在 class UserImages 中没有任何 userId,但有用户 class 的参考,那么如何根据 userId 添加或更新或删除 userImages。
  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? 1.如果这是正确的想法和制作所有者实体?

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 2. 我在 class UserImages中没有任何userId ,但有Users class 的参考,那么如何根据userId添加或更新或删除userImages

Since you have the reference of Users in UserImages , you can get userImages by users itself.由于您在UserImages中有Users的引用,因此您可以通过users自己获取userImages Hibernate will do that for you. Hibernate将为您做到这一点。 If you still want to get userImages by userId , you can do so as well by users.getId() - which will give you userId如果您仍想通过userId获取userImages ,您也可以通过users.getId()来获取 - 这将为您提供userId

Spring-data will automatically provide you such serves methods - Spring-data将自动为您提供此类服务方法 -

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.首先你要决定在ORM层,即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.就“所有者实体”而言,您必须告诉 hibernate 谁是关系的所有者,即谁拥有外键的引用。 You can do it either using @JoinColumn or mappedBy , in bidirectional use both.您可以使用@JoinColumnmappedBy来实现,双向使用两者。
@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.如果您的Users实体是持久的,那么当您从userImagesList中删除一些图像时,它将与数据库同步。 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 .当负责从列表中删除该图像的方法完成时(或者当您制作entityManager.flush()时),该图像将从数据库中删除,因为CascadeType In bidirectional mapping removing should be done by your synchronization remove method.在双向映射中删除应该由您的同步删除方法完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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