Iam using Spring Hibernate with JPA. cascade=CascadeType.ALL and @Id @GeneratedValue(strategy = GenerationType.IDENTITY). I have two tables one is User the other is photos when I want to add a new photo do I need to go and take the User from the database and then set it as a user in the photo with photo.setUser(user). Is there a way to just do User user = new User(); user.setId(1) and then put it in the photo with photo.setUser() without a full reference I am getting detached entity passed to persist when I execute repo.save(photo) when I am setting only the id.
What I want to do is:
User user = new User();
user.setId(1);
photo.setUser(user);
repo.save(photo)
Where user is already created in the database and has several photos.
instead of:
User user = repo.findUserById(1);
photo.setUser(user);
repo.save(photo);
my entities:
@Entity
@Table(name = "users")
public class Photo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToMany(cascade = CascadeType.ALL,mappedBy = "user", fetch = FetchType.EAGER)
private List<Photo> photos = new ArrayList<>();
@Entity
@Table(name = "photos")
public class Photo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;