我发现我可以@JoinColumn
加入两个表格。例如,我在profile_photo_id
表中有usr
映射到photo
表。我得到的Usr
对象将有一个photo
对象而不是int。
我现在遇到的问题是我有一个列photoIds
,它是一个整数数组,其中id与photo
表相关联。如何正确地将我的int数组映射到photo
对象的数组?我正在使用postgresql。
EDITED
@Entity
@Table(name = "usr")
public class Usr {
@Id
@Setter
@Getter
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
@Getter
@Setter
private String name;
@Getter
@Column(name = "updated_at", insertable = false, updatable = false)
private Date updatedAt;
@Getter
@Column(name = "created_at", insertable = false, updatable = false)
private Date createdAt;
@Getter
@Setter
@Column(name = "photo_ids")
private Integer[] photoIds; // ideally is to convert this to array of photo object
}
然后是照片实体
@Entity
@Table(name = "photo")
public class Photo {
@Id
@Setter
@Getter
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
@Setter
@Getter
private String url;
}
我的usr表
root::DATABASE=> \d+ usr
Table "public.usr"
Column | Type | Modifiers | Storage | Stats target | Description
---------------------+--------------------------------+---------------------------------------------------+----------+--------------+------------------------------------------
id | integer | not null default nextval('usr_seq'::regclass) | plain | |
name | character varying(255) | | extended | |
updated_at | timestamp(0) without time zone | default now() | plain | |
created_at | timestamp(0) without time zone | not null default now() | plain | |
photo_ids | integer[] | | extended | |
答案 0 :(得分:0)
尝试将您的pojo修改为以下
@Entity
@Table(name = "usr")
public class Usr {
@Id
@Setter
@Getter
@GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
@Getter
@Setter
private String name;
@Getter
@Column(name = "updated_at", insertable = false, updatable = false)
private Date updatedAt;
@Getter
@Column(name = "created_at", insertable = false, updatable = false)
private Date createdAt;
@Getter
@Setter
@OneToMany(name = "photo_ids")
private List<Photo> photos = new ArrayList<Photo>();
}
这将给出一个&#39; Photo&#39;对象的数组。最佳做法是设置&#39; hibernate.hbm2ddl&#39;自动这将使您免于将POJO与数据库表匹配的艰苦工作。