简体   繁体   English

如何在 Springboot 中向实体集合添加新条目

[英]How to add new entries to an entity's collection in Springboot

Let's say there is a class as follows:假设有一个 class 如下:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
class OauthUser(
    @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.EAGER)
    var oauthAttributes: List<OauthAttribute>,

    @NotNull
    @Column(unique = true)
    var email: String,
    var firstName: String,
    var lastName: String
) : OAuth2User {

    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    var id: Long? = null

}

I am trying to add new entries of oauthAttributes when a user logs in again after initially logging in, so that if there is an updated attribute, a new attribute is created to keep a history of profle changes.我正在尝试在用户首次登录后再次登录时添加新的oauthAttributes条目,以便如果有更新的属性,则会创建一个新属性以保留配置文件更改的历史记录。

I am not able to userRepository.findByEmail(email).oauthAttributes.add(newEntry) because oauthAttributes is defined as a List, which doesn't have the add method.我无法userRepository.findByEmail(email).oauthAttributes.add(newEntry)因为 oauthAttributes 被定义为一个列表,它没有添加方法。 When I try to cast it to ArrayList I get the following error: java.lang.ClassCastException: class org.hibernate.collection.internal.PersistentBag cannot be cast to class java.util.ArrayList .当我尝试将其转换为 ArrayList 时出现以下错误: java.lang.ClassCastException: class org.hibernate.collection.internal.PersistentBag cannot be cast to class java.util.ArrayList

How can I go about adding an entry into that lits?我怎样才能 go 在那个 lits 中添加一个条目?

After doing some reading and experimenting I found that the following works:在做了一些阅读和实验之后,我发现以下工作:

  1. Create a reference to the user in the OauthAttribute class, like so:OauthAttribute class 中创建对用户的引用,如下所示:
    @ManyToOne
    @JoinColumn(name = "user_id")
    @NotNull
    lateinit var user: OauthUser
  1. Adjust the oauthAttributes collection definition in the OauthUser class, from调整OauthUser class 中的oauthAttributes集合定义,从
    @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.EAGER)
    var oauthAttributes: List<OauthAttribute>,

to

    @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.EAGER, mappedBy = "user")
    var oauthAttributes: List<OauthAttribute>?

This will create a user_id foreign key reference in the oauth_attribute table instead of a separate join table.这将在 oauth_attribute 表中创建一个user_id外键引用,而不是单独的连接表。 Now it is possible to simply create new instances of the OauthAttribute class and assign them to the user by simply specifying assigning the user class property to the corresponding user.现在可以简单地创建OauthAttribute class 的新实例并将它们分配给用户,方法是简单地指定将user class 属性分配给相应的用户。

I welcome any comments in case that solution isn't optimal.如果解决方案不是最佳的,我欢迎任何评论。 Also, I believe the question still stands for many to many relationships.另外,我相信这个问题仍然代表多对多关系。

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

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