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

时间:2017-09-09 12:49:32

标签: spring spring-boot spring-data-jpa

我是春天的新人。我想将数据插入AUDIT表。 USERAUDIT表之间存在一对两的关系。

对于每个登录和注销,应将数据插入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);

}

1 个答案:

答案 0 :(得分:1)

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