gpt4 book ai didi

spring - 如何在spring jpa中以一对多关系插入数据

转载 作者:行者123 更新时间:2023-12-04 17:49:38 26 4
gpt4 key购买 nike

我是 Spring 的新人。我想将数据插入到 AUDIT 表中。 USER 表和AUDIT 表之间存在一对二多关系。

对于每个登录和注销数据都应该插入到AUDIT 表中。我该怎么做?

用户实体:

@Table(name="USER")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="USERID")
private Long id;

private String username;

private String email;

private Long phone;

private String password;

private int OTP;

private boolean activation_flag;

@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="USERID")
private Set<Audit> audit;

@ManyToOne
@JoinColumn(name="ADDRESSID")
private Address address;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "USER_AUTHORITY",
joinColumns = {@JoinColumn(name = "USER_ID", referencedColumnName = "USERID")},
inverseJoinColumns = {@JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")})
private List<Authority> authorities;

审计实体:

@Entity
@Table(name="AUDIT")
public class Audit {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="AUDITID")
private long auditid;

@Column(name="GEOLOCATION")
private String geolocation;

@Column(name="ACTION")
private String action;

@Column(name="DATETIME")
private Date datetime;

@Column(name="DEVICEID")
private long deviceid;

@Column(name="ACTIONSUCCESS_FAIL")
private boolean actionsuccess_fail;

@Column(name="JWT_TOKEN")
@Type(type="text")
private String JWT_token;

@ManyToOne
private User user;

审计存储库:

public interface AuditRepository extends JpaRepository<Audit, Long> {
}

用户存储库:

public interface UserRepository extends JpaRepository<User, Long> {

User findByUsername(String username);
User findByEmail(String email);
User findByPhone(Long phone);
User findById(Long id);

}

最佳答案

将审核添加到您希望审核关联的用户,然后保存。

关于spring - 如何在spring jpa中以一对多关系插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com