Hey Marcel,
I did a similar example and it is working for me. Check if you can find any differences here:
Code:
package test.model.data.jpa;
import javax.persistence.*;
@Entity
@Table(name = "CAR")
public class Car {
private Long id;
private String name;
private Stereo stereo;
@Id
@GeneratedValue
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
@JoinColumn(name = "STEREO_ID")
public Stereo getStereo() {
return stereo;
}
public void setStereo(Stereo stereo) {
this.stereo = stereo;
}
}
and the other side of relation with the same options you had put except @Basic since it is redundant:
Code:
package test.model.data.jpa;
import org.hibernate.annotations.*;
import javax.persistence.CascadeType;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "STEREO")
public class Stereo {
private Long id;
private String name;
private List<Car> cars = new ArrayList<Car>(2);
@Id
@GeneratedValue
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "stereo", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@OrderBy("name ASC")
@OnDelete(action = OnDeleteAction.CASCADE)
@LazyToOne(LazyToOneOption.PROXY)
@LazyCollection(LazyCollectionOption.TRUE)
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}
and the query is:
Code:
Query query = em.createQuery("from Stereo s where s.name = :name");
query.setParameter("name", "JVC 101");
final Stereo stereo = (Stereo) query.getSingleResult();
It only fetches the stereo and no list of cars afterwards.
Bests,
Farzad-