简体   繁体   English

Hibernate:在Spring中保存复杂的数据模型

[英]Hibernate: Saving a complex data model in Spring

My data model has a network of entities. 我的数据模型有一个实体网络。 A set of entities that reference each other with @OneToOne , @ManyToOne , etc. Some of these references are defined to be @NotNull 一组相互引用与实体@OneToOne@ManyToOne等。一些这些参考文献的定义为@NotNull

@Entity
@Table(name="UserDetails")
public class CustomUserDetails implements Serializable {
    @NotNull
    @JoinColumn(name="user_id", referencedColumnName="id")
    @OneToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private User user;
    //.....
}

CustomUserDetailsService handles saving and loading instances of CustomUserDetails class from the DB and UserDetailsRepository is an interface that extends CrudRepisitory . CustomUserDetailsService处理从数据库保存和加载CustomUserDetails类的实例,而UserDetailsRepository是扩展CrudRepisitory的接口。

When user makes a call to /signup we want to create and save an instance of CustomUserDetails to the db. 当用户调用/signup我们要创建CustomUserDetails实例并将其保存到数据库。 But before server persists a new instance of CustomUserDetails , it has to create a new instance of type User and save it to the db (as it is defined as @NotNull ). 但是在服务器持久CustomUserDetails的新实例CustomUserDetails ,它必须创建User类型的新实例并将其保存到db(定义为@NotNull )。

Does it makes sense to do this in CustomUserDetailsService , in the Controller? 在Controller的CustomUserDetailsService执行此操作是否有意义? or where else ? 还是其他地方?

I'm afraid that the design gets too complex and there would be lots of cross references between service classes of different entities when the data model gets more complicated. 恐怕设计会变得太复杂,并且当数据模型变得更复杂时,不同实体的服务类之间会有很多交叉引用。

Following the same style, you should have a class called something like "UserService" , that handles CRUD operations for users. 遵循相同的样式,您应该具有一个名为“ UserService”的类,该类为用户处理CRUD操作。 Class CustomUserDetailsService should hold a member that is UserService , preferably using @Autowire annotation. CustomUserDetailsS​​ervice应该包含一个UserService成员,最好使用@Autowire注释。

Before creating a new custom user details, call the UserService to create a new user (if needed). 在创建新的自定义用户详细信息之前,请调用UserService来创建新用户(如果需要)。

In principle it could end here, CustomUserDetailsService is familiar with UserService , but vice versa. 从原则上讲 ,它可以在这里结束, CustomUserDetailsS​​ervice熟悉UserService ,反之亦然。 You have defined cascade=CascadeType.ALL , so if you delete a user, the customer user details are also deleted. 您已经定义了cascade = CascadeType.ALL ,因此,如果删除用户,则还将删除客户用户详细信息。

Just make sure that other relations the CustomUserDetails have their cascade defined correctly. 只需确保CustomUserDetails的其他关系具有正确定义的级联即可。

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

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