I am taking my first steps into jpa (porting the whole db from jdbc to jpa) and i was wondering how i can achieve the following: I have two tables, a Users table and a ProfileImages table, the ProfileImages table consists in a FK to user_id and then another field which is a byte array (which holds the image's bytes).
What i am trying to achieve is being able to recover the byte array directly in my User model, something in the lines of:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_userid_seq")
@SequenceGenerator(name = "users_userid_seq", sequenceName = "users_userid_seq", allocationSize = 1)
private Long userId;
@Column
private String name;
@Column
private String surname;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false, unique = true)
private String email;
@Column
private String password;
@Column(nullable = false, unique = true)
private Integer fileNumber;
@Column
private boolean isAdmin;
// Map the byte array from the profile_image relation
private byte[] image;
.....
.....
}
Note: It'd be optimal to not change the schema to make the user hold the byte array.
CodePudding user response:
You can use the SecondaryTable
annotation to map two tables to one Entity
:
@Entity
@Table(name = "users")
@SecondaryTable(name = "profileimages",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "user_id"))
public class User {
@Column(name = "image", table = "profileimages")
private byte[] image;
Please also check out the documentation: https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#sql-custom-crud-secondary-table-example