对于一个学校项目,我们必须制造一个Spring Boot Rest服务器来与我们的MySQL数据库进行通信。这是数据库的屏幕截图:
对于我的用户模型,我有以下内容:
@Entity
@Table(name = "User")
@Setter
public class User extends ResourceSupport implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_user", updatable = false, nullable = false)
@JsonSerialize
private Long id;
@Getter
private String firstName;
@Getter
private String lastName;
@Getter
private String email;
@Getter
private String password;
@Getter
private Double hourlyWage;
@Getter
private String adress;
@Getter
private String city;
@Getter
private Boolean isManager;
@Getter
@OneToMany
@JoinTable(name = "user_to_project", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "project_id"))
private List<Project> projects;
然后针对我的项目班级:
@Entity
@Table(name = "project")
@Setter
public class Project extends ResourceSupport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_project")
@JsonSerialize
private Long id;
@Getter
@OneToOne
@JoinColumn(name = "owner", referencedColumnName = "id")
private Company owner;
@Getter
private String description;
@Getter
private String name;
@Getter
private double payout;
@Getter
private boolean internal;
@Getter
@OneToMany
@JoinTable(name = "user_to_project", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
private List<User> users;
我不知道自己在做什么错,因为这是我得到的结果:
在链接表中有此链接时
我希望有人能回答我的问题,因为我厌倦了春季靴子和这个学校项目。
答案 0 :(得分:1)
我不知道它对您有没有帮助,但是下面是我的代码:
// Role
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany(mappedBy = "roles")
@JsonIgnoreProperties("roles")
@OrderBy("id")
private List<User> users;
// User
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany
@JoinTable(name = "users_roles",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")
)
@JsonIgnoreProperties("users")
@OrderBy("id")
private List<Role> roles;
还请注意-在JPA中,一个表是“ master”(在我的示例中为User),而另一个表是“ slave”,而不是m2m表相等的SQL。 “从属”在@ManyToMany批注中应具有修饰符mappedBy
。
表DDL(postgres):
create table roles
(
id serial not null
constraint roles_pkey
primary key,
version bigint default 0
);
create table users
(
id serial not null
constraint users_pkey
primary key,
version bigint default 0
);
create table users_roles
(
user_id integer not null
constraint fk_users
references users,
role_id integer not null
constraint fk_roles
references roles,
constraint users_roles_pkey
primary key (user_id, role_id)
);
我希望它将对您有所帮助。祝你好运。