Hello,
I’m not used to ask for help but I’m really stuck for a few days. No way to find the same issue on Stackoverflow or Google...
I have two entities Event and Artist with a many-to-many relationship. The join table is EventArtists.
Code:
Event <-- EventArtists --> Artist
ArtistCode:
@Entity
public class Artist {
@Id
@GeneratedValue
private Long idArtist;
private String name;
private String description;
@ManyToMany(mappedBy = "artists")
private Set<Event> events = new HashSet<Event>();
EventCode:
@Entity
public class Event {
@Id
@GeneratedValue
private Long idEvent;
private String name;
private String description;
@ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
@JoinTable(name="EventArtists",
joinColumns=
@JoinColumn(name="idEvent"),
inverseJoinColumns=
@JoinColumn(name="idArtist")
)
private Set<Artist> artists = new HashSet<Artist>();
I’m trying to fetch an event and its associated artists using a native query. According to the documentation, I’m using addEntity and addJoin. Since the two entities are mapped to the same column names (id, name, description), I also use aliases.
Here is my request:
Code:
NativeQuery nativeQuery = session.createNativeQuery("SELECT {e.*}, {a.*} "+
"FROM Event e "+
"LEFT JOIN EventArtists ea ON e.idEvent = ea.idEvent "+
"LEFT JOIN Artist a ON a.idArtist = ea.idArtist "+
"WHERE e.idEvent = :id");
nativeQuery.addEntity("e", Event.class)
.addJoin("a", "e.artists")
.setParameter("id", 1);
nativeQuery.getResultList();
nativeQuery.getResultList() throws the following exception :
Quote:
org.h2.jdbc.JdbcSQLException: Column "A.IDEVENT" not found
Indeed, Hibernate doesn’t generate correctly the request. It looks for columns "a.idEvent as idEvent1_2_0__, a.idArtist as idArtist2_2_0__", which are EventArtists's columns.
We get:
Quote:
SELECT e.idEvent as idEvent1_1_0_, e.description as descript2_1_0_, e.name as name3_1_0_, a.idEvent as idEvent1_2_0__, a.idArtist as idArtist2_2_0__, a.idArtist as idArtist1_0_1_, a.description as descript2_0_1_, a.name as name3_0_1_ FROM Event e LEFT JOIN EventArtists ea ON e.idEvent = ea.idEvent LEFT JOIN Artist a ON a.idArtist = ea.idArtist WHERE e.idEvent = ?
instead of
Quote:
SELECT e.idEvent as idEvent1_1_0_, e.description as descript2_1_0_, e.name as name3_1_0_, a.idArtist as idArtist1_0_1_, a.description as descript2_0_1_, a.name as name3_0_1_ FROM Event e LEFT JOIN EventArtists ea ON e.idEvent = ea.idEvent LEFT JOIN Artist a ON a.idArtist = ea.idArtist WHERE e.idEvent = ?
Your assistance will be very much appreciated.
Thank you