My scenario is a users table and a pictures table. Each user can upload multiple pictures. Each user can set one of their own pictures to be their favourite picture, but this does not affect that picture being within that user’s collection of pictures.
Mapping this to hibernate has proven to be difficult. My application has a screen which displays a list of all of a user’s pictures, and also says which one is their favourite. However, when the application loads the pictures, the single picture which is the favourite one does not load. Debugging in eclipse shows various fun things for that specific object in the list, perhaps it is a proxy object. Here is the entity code showing the mappings:
@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;
}
I do not know why the favourite picture fails to load in the list of pictures. Any suggestions will be highly appreciated 😀
Since a
Picturehas a specificAccountwhich owns it I would be tempted just to include a boolean property on the Picture class calledisFavourite. This would simplify the mappings considerably.You could provide a
getFavouritemethod on the Account class which returns the favourite picture by looking through the list of pictures and finding the one marked as favourite.