I'm working with Spring Boot and JPA and I have a many-to-many relationship between two tables. This relationship also needs to have its own attributes, so I had to make this relationship its own class. I also have repositories for all classes. Also, how would I map foreign keys correctly when using non-primitive fields?
My question: How do I realize this so Spring boot does not give me an error? I'm new to both Spring Boot and JPA. Here's a code snippet below:
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity //this is a relationship type. Does an annotation for relationship types exist?
@Embeddable
@Getter
@Setter
@NoArgsConstructor
public class RelationshipType implements Serializable {
@Id
private Long id;
@NotNull
@JoinColumn(name="id")
private Class1 class1;
@NotNull
@JoinColumn(name="code")
private Class2 class2;
private Integer anotherNumber;
}
It should look similar to the example below. You need to set the relations to the other tables as @ManyToOne
to get the desired @ManyToMany
relation between Employee and Number.
@Entity
@Getter
@Setter
@Table(name = "employees_numbers")
public class EmployeeNumber {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id", nullable = false)
private Employee employee;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "number_id", nullable = false)
private Number number;
@Column(name = "extra_column", nullable = false)
private String extraColumn;
}
Side note: don't use @NotEmpty
on Integer. It is specifically made for collections.
Side note 2: I'll go on a limp here and say what you want is to add nullable = false
to the columns and not mark them as @NotNull
. There is a significant difference between the two.