I have this entity:
@Getter
@Setter
@Entity
@Table(name = "publications")
public class Publication {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "publication_id")
private Long id;
@NotBlank
@Column(name = "titie", nullable = false)
private String title;
@NotBlank
@Column(name = "text", nullable = false, columnDefinition = "TEXT")
private String text;
@ManyToOne
@JoinColumn(name = "author_username", nullable = false)
private User author;
@CreationTimestamp
@Column(name = "publication_date", nullable = false)
private Instant publicationDate;
@OneToMany
@JoinTable(
name = "publications_files",
uniqueConstraints = @UniqueConstraint(columnNames = {"file_id", "publication_id"}),
joinColumns = @JoinColumn(name = "publication_id"),
inverseJoinColumns = @JoinColumn(name = "file_id")
)
private List<File> files;
}
When I press "show DDL" and select PostgreSQL as my database it gives me the following result:
CREATE TABLE publications
(
publication_id BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
titie VARCHAR(255) NOT NULL,
text TEXT NOT NULL,
author_username VARCHAR(50) NOT NULL,
publication_date TIMESTAMP WITHOUT TIME ZONE NOT NULL,
CONSTRAINT pk_publications PRIMARY KEY (publication_id)
);
CREATE TABLE publications_files
(
file_id BIGINT NOT NULL,
publication_id BIGINT NOT NULL
);
ALTER TABLE publications_files
ADD CONSTRAINT uc_publications_files_file UNIQUE (file_id);
ALTER TABLE publications
ADD CONSTRAINT FK_PUBLICATIONS_ON_AUTHOR_USERNAME FOREIGN KEY (author_username) REFERENCES users (username);
ALTER TABLE publications_files
ADD CONSTRAINT fk_pubfil_on_file FOREIGN KEY (file_id) REFERENCES files (file_id);
ALTER TABLE publications_files
ADD CONSTRAINT fk_pubfil_on_publication FOREIGN KEY (publication_id) REFERENCES publications (publication_id);
I expected unique constraint for table publication_files with file_id and publication_id. But got just file_id in unique constraint. When I changed PostgreSQL to MySQL the result was the same. What do I wrong? Is it a bug ?
Yes, this is a bug, I created a ticket to fix it https://issues.jpa-buddy.com/issue/JPAB-2655
Also, if files
collect unique elements, you can use Set
instead of List
- in this case JPA Buddy will generate a primary key for file_id + publication_id
, and the unique constraint will not be needed.