Hi folks,
I have mapped a ManyToMany relationship and successfully retrieved data from the DB. Now I would like to persist more data into the DB.
Here's what I've done:
in Dog.java:
Code:
@ManyToMany(
cascade={CascadeType.PERSIST, CascadeType.MERGE},
mappedBy="dogs",
targetEntity=Photo.class,
fetch=FetchType.EAGER
)
private List<Photo> photos;
public List<Photo> getPhotos(){return photos;}
public void setPhotos(List<Photo> photos){
this.photos = photos;
}
in Photo.java
Code:
@ManyToMany(
targetEntity=Dog.class,
cascade={CascadeType.PERSIST, CascadeType.MERGE},
fetch=FetchType.EAGER
)
@JoinTable(
name="dogphoto",
joinColumns={@JoinColumn(name="photoId")},
inverseJoinColumns={@JoinColumn(name="dogId")}
)
private List<Dog> dogs;
public List<Dog> getDogs(){return dogs;}
public void setDogs(List<Dog> dogs){
this.dogs = dogs;
}
And here's how I tried to use it:
Code:
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
IDogDAO dogDao = DAOFactory.DEFAULT.getDogDAO();
Dog hurley = dogDao.findById(3, false);
File file = new File("D:\\Dany's Stuff\\My Pictures\\Berners\\Hurley (Luke)\\First Birthday\\Hurley_1st_BDay_Portrait.jpg");
byte[] imageByte = ImageUtil.FileToByteArray(file);
Photo photo = new Photo();
photo.setImage(imageByte);
hurley.getPhotos().add(photo);
photo.getDogs().add(hurley);
dogDao.makePersistent(hurley);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
I'm sure I'm not doing it right here - I get a NullPointerException at the line
Code:
photo.getDogs().add(hurley);
Can someone please help me with this? I'm frustratingly close to get it working - or at least that's what I thought...
Thanks,
Dany.