如何在Hibernate中将一组id映射到其他表?

时间:2017-08-31 01:40:05

标签: postgresql hibernate

我发现我可以@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 |              |

1 个答案:

答案 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与数据库表匹配的艰苦工作。