I have 2 SQL tables:
Users:
CREATE TABLE users
(
id BIGINT PRIMARY KEY DEFAULT nextval('global_seq'),
/* email, password, other fields */
);
Users_avatars:
CREATE TABLE users_avatars
(
user_id BIGINT NOT NULL,
file_name VARCHAR,
file_path VARCHAR,
FOREIGN KEY (user_id) REFERENCES users (id)
);
However, why I try to map it with Hibernate it creates file_name
and file_path
inside the users
table.
My classes are the following:
@Entity
@Table(name = "users")
@SecondaryTable(name = "users_avatars",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "user_id", referencedColumnName = "id"))
public class User extends EntityWithId
{
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "file_name", column = @Column(table = "users_avatars")),
@AttributeOverride(name = "file_path", column = @Column(table = "users_avatars"))
})
private FileInDb avatar;
public FileInDb getAvatar()
{
return avatar;
}
public void setAvatar(FileInDb avatar)
{
this.avatar = avatar;
}
}
And FileInDb class:
@Embeddable
@MappedSuperclass
public abstract class FileInDb
{
@Column(name = "file_name")
@NotNull
@NotBlank
private String fileName;
@Column(name = "file_path")
@NotNull
@NotBlank
private String filePath;
public String getFileName()
{
return fileName;
}
public void setFileName(String fileName)
{
this.fileName = fileName;
}
public String getFilePath()
{
return filePath;
}
public void setFilePath(String filePath)
{
this.filePath = filePath;
}
}
SQL script generated by Hibernate:
create table users (
id int8 not null,
file_name varchar(255),
file_path varchar(255),
/* Lots of other fields */
primary key (id)
)
create table users_avatars (
user_id int8 not null,
primary key (user_id)
)
Why is so? Please help. Thanks in advance.
您可以将@OneToOne映射与@MapsId一起使用,以将user_id用作user_avatars表的id字段
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.