I got a question regarding hibernate. I have to classes with many to many relationship and try to make a select. The problem is I am getting an exception. Can you help?
@Entity(name = "pracownik")
@Inheritance(strategy = InheritanceType.JOINED)
@Proxy(lazy = false)
public class Pracownik extends Osoba {
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinTable(name = "grafikpracownika", joinColumns = { @JoinColumn(name = "idosoby") },
inverseJoinColumns = { @JoinColumn(name = "idgrafiku") })
private List<Grafik> grafiki = new ArrayList<>();
}
The second entity
@Entity (name = "grafik")
@Proxy(lazy = false)
public class Grafik {
@ManyToMany (mappedBy = "grafiki",cascade = { CascadeType.ALL })
private List <Pracownik> pracownik = new ArrayList<>();
}
The method I developed is:
public List<Pracownik> getWszyscyPracownicyGrafiku() {
List<Pracownik> pracownicy = new ArrayList<>();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("from pracownik as p join p.grafiki");
pracownicy = query.list();
transaction.commit();
return pracownicy;
}
And the exception is:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to model.Pracownik
Any idea what is wrong?
I also would like to add a "where" but it should be easy after I get rid of this exception. I also tried with "normal" sql
SELECT * from pracownik p join grafikpracownika g on p.idosoby = g.idosoby where idgrafiku = 6
but what I am getting is:
org.hibernate.loader.custom.NonUniqueDiscoveredSqlAliasException: Encountered a duplicated sql alias [idosoby] during auto-discovery of a native-sql query
You're selecting from two tables without explicit select
clause, therefore Hibernate produces a list of tuples (Pracownik, Grafik)
as a result.
If you want only Pracownik
s (i.e. join is needed to create condition on p.grafiki
in where
), use
select distinct p from pracownik as p join p.grafiki
If join is used to instruct Hibernate to fetch associated Grafik
s, use join fetch
:
from pracownik as p join fetch p.grafiki
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments