3

I am new in Spring. I want to insert the data into the AUDIT table. There is a one-two-many relationship between USER and AUDIT tables.

For every login and logout data should be inserted into the AUDIT table. How can I do that?

The user entity:

@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; 

The audit entity:

@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; 

The audit repository:

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

The user repository:

public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); User findByEmail(String email); User findByPhone(Long phone); User findById(Long id); } 
2
  • I've improved formatting (for better readability and hopefully more answers) Commented Sep 9, 2017 at 13:44
  • Thomas Fritsch thank you Commented Sep 9, 2017 at 13:47

1 Answer 1

1

Add the audit to the user you want the audit associated with, then save.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanku letsBeFrank..can you please tell me how can I insert data in one to many relationships..
user.getAudits().add(newAudit); then userRepository.save(user);
any one have answer i want to add through REST api

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.