我有两个模型,即公司和用户。 公司可以有很多用户。我使用Spring数据jpa与数据库进行交互。
用户模型:
REQ/REP
公司模式
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(length = 50, unique = true)
@NotNull
@Size(min = 4, max = 50)
private String username;
@NotNull
@Size(min = 8)
private String password;
@Column(length = 50)
@NotNull
@Size(min = 4, max = 50)
private String firstName;
@Column(length = 50)
@NotNull
@Size(min = 4, max = 50)
private String lastName;
@Column(length = 50, unique = true)
@NotNull
@Size(min = 4, max = 50)
private String email;
private Boolean enabled = true;
@Temporal(TemporalType.TIMESTAMP)
@UpdateTimestamp
private Date lastPasswordReset;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt = new Date();
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@UpdateTimestamp
@LastModifiedDate
private Date updatedAt = new Date();
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
name = "user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_id", referencedColumnName = "id")})
private List<Authority> authorities;
@ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JsonBackReference
private Company company;
... Getter and Setters
}
所以我使用Spring Data JPA来保存公司,它也负责创建用户。 所以今天如果由于某种原因导致用户的创建因某些异常而失败,那么公司记录仍然存在。 所以我需要,如果创建用户失败,则不会创建公司(回滚)。 我怎样才能做到这一点。