【问题标题】:Hibernate Annotations: Two relation types between two entities?Hibernate Annotations:两个实体之间的两种关系类型?
【发布时间】:2012-08-21 06:52:37
【问题描述】:

我的场景是一个用户表和一个图片表。每个用户可以上传多张图片。每个用户都可以将自己的一张图片设置为他们最喜欢的图片,但这并不影响该图片在该用户的图片集合中。

将其映射到休眠已被证明是困难的。我的应用程序有一个屏幕,其中显示了所有用户图片的列表,并且还说明了哪一张是他们最喜欢的。但是,当应用程序加载图片时,最喜欢的单张图片不会加载。在 Eclipse 中调试会为列表中的特定对象显示各种有趣的东西,也许它是一个代理对象。这是显示映射的实体代码:

@Entity
class Account {
    @Id
    public String username;

    /* Originally a Set<Picture>, but wanted ordering */
    @OneToMany(cascade=CascadeType.ALL, mappedBy="account")
    @OrderBy("uploadtime DESC")
    public List<Picture> pictures;

    @ManyToOne(fetch = FetchType.LAZY, optional=true)
    @LazyToOne(LazyToOneOption.PROXY)
    @JoinColumn(name="favourite_picture_id")
    public Picture favourite_picture;

    /* Sometimes it is useful to get just the id, if possible without loading the entire entity */
    @OneToOne(fetch = FetchType.LAZY, optional=true)
    @Column(insertable=false, updatable=false)
    public String favourite_picture_id;
}

@Entity
public class Picture {
    @Id
    @GeneratedValue(generator="uuid")
    @GenericGenerator(name="uuid", strategy="uuid2")
    public String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="username")
    public Account account;

    /* This is never used, but I thought this might be required for the mapping? */
    @OneToOne(mappedBy="favourite_picture")
    public Account account_favourite_picture;


    public String mimetype;

    public Date uploadtime = new Date();

    @Column(length=1024 * 1024 * 4)
    public byte[] data;
}

我不知道为什么收藏的图片无法加载到图片列表中。任何建议将不胜感激:D

【问题讨论】:

    标签: java mysql hibernate orm annotations


    【解决方案1】:

    由于Picture 有一个特定的Account 拥有它,我很想在名为isFavourite 的图片类中包含一个布尔属性。这将大大简化映射。

    您可以在 Account 类上提供一个getFavourite 方法,该方法通过查看图片列表并找到标记为收藏的那张来返回收藏的图片。

    【讨论】:

    • 这是解决问题的有趣方法。我正在使用 List 映射,因为我希望每个帐户只有少量图片,所以它可能是可以接受的。完美主义不能妨碍拥有一个功能系统。您也启发了另一个想法,我可以在 Account 实体中使用一个字符串来存储最喜欢的图片的 ID,并且我可以在 Account 中实现 getFavourite() 方法,该方法通过列表查找匹配的图片。这可能是我会做的,除非很快有更好的帖子。感谢您的建议。
    • 没问题。如果可能的话,我的目标是避免复杂的映射。我总是更喜欢更简单的方法!
    • 简单真的是最好的,现在一切都在使用更简单的映射。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2021-05-06
    • 2021-01-26
    相关资源
    最近更新 更多