第一次使用SpringBoot和Hibernate。
我在画我的地图
和
角色.java
类到NetBeans中的MySQL数据库。除了一个细节,一切都很好。
当我在
服务
user_role
表(@ManyToMany的结果),它允许我,即使还没有创建用户或角色。我希望它会提示我一些错误,比如说我插入的用户ID不存在。
pgAdmin公司
好吧,这是一个重大的不。
如果这是默认行为,请告诉我如何重写它,如果不是,这是我的代码,其中有错误。
用户.java
package hello;
import java.util.Set;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Transient;
@Entity // This tells Hibernate to make a table out of this class
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String email;
private String username;
private String password;
private String passwordConfirm;
@ManyToMany(targetEntity = Role.class)
@Access(AccessType.FIELD)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Transient
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
package hello;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "role")
public class Role {
private Long id;
private String name;
@ManyToMany(targetEntity = User.class, mappedBy = "roles")
@Access(AccessType.FIELD)
private Set<User> users;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
如果你需要更多的信息,请询问。