I have two entities:
#Entity
#Table(name = "ACCOUNT")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class MyCloudAccount implements Serializable {
...
#OneToMany(mappedBy = "account", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<ServerInstance> servers = new HashSet<ServerInstance>();
...
}
#Entity
#Table(name = "SERVER_INSTANCE")
public class ServerInstance implements Serializable {
...
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ACCOUNT_ID")
private MyCloudAccount account;
...
}
I am getting all accounts by this code:
StringBuilder sql = new StringBuilder();
sql.append("SELECT e FROM ");
sql.append(persistentClass.getName());
sql.append(" e");
return entityManager.createQuery(sql.toString()).getResultList();
And this produces one query for the account and N queries for the servers instead of one with outer join. How to force JPA to make the query in optimal way?
I find it more convenient to use Java Persistence Query Language
you can do:
#NamedQueries{
#NamedQuery(name="myQuery" query="SELECT a FROM MyCloudAccount JOIN FETCH a.servers")
}
public class MyCloudAccount{
...
}
then you can do
TypedQuery<MyCloudAccount> query = em.createNamedQuery("MyCloudAccount.myQuery", MyCloudAccount.class);
List<MyCloudAccount> results = query.getResultList();
EDIT
You are actually already using JPQL. The key thing to your problem is using the JOIN FECTH command.
Related
In my spring boot application, I have two entities: ScheduledLegEntity and BookingLegEntity.
#Entity
#Table(name="SCHEDULED_LEG")
public class ScheduledLegEntity {
// ...
#OneToMany(mappedBy = "getOn", cascade = CascadeType.MERGE)
private List<BookingLegEntity> enteringBookingLegs;
#OneToMany(mappedBy = "getOff", cascade = CascadeType.MERGE)
private List<BookingLegEntity> exitingBookingLegs;
// ...
}
#Entity
#Table(name = "BOOKING_LEG")
public class BookingLegEntity {
// ...
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "GET_ON")
private ScheduledLegEntity getOn;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "GET_OFF")
private ScheduledLegEntity getOff;
// ...
}
Now, I need to query my database for a specific set of scheduled legs and I also need to work with their enteringBookingLegs and exitingBookingLegs. I quickly stumbled accross this exception:
rg.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: de.mopla.server.schedule.entities.ScheduledLegEntity.enteringBookingLegs, could not initialize proxy - no Session
I tried solving this (and the subsequent MultipleBagFetchException) problem by following this guide on baeldung ("8. Ideal Solution: Using Multiple Queries
") like this:
public class CustomScheduledLegRepositoryImpl implements CustomScheduledLegRepository {
#PersistenceContext
private EntityManager entityManager;
#Override
public List<ScheduledLegEntity> customFindMethod(){
List<ScheduledLegEntity> legs = entityManager.createQuery(
"select distinct p from ScheduledLegEntity p left join fetch p.enteringBookingLegs", ScheduledLegEntity.class)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();
legs = entityManager.createQuery("select distinct p from ScheduledLegEntity p left join fetch p.exitingBookingLegs t where p in :legs", ScheduledLegEntity.class)
.setParameter("legs", legs)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();
return legs;
}
}
But even with those two queries, only either enteringBookingLegs or exitingBookingLegs are empty (see screenshots from debugging). How can I solve this problem (efficiently)?
As you can see, only one of the lists can be accessed, first exitingBookingLegs and then enteringBookingLegs, but never both at the same time.
I've got 3 entity classes:
(The BaseAutoIncrementModel contains the declaration of the id for each entity)
Table 1: Dossier
#Entity
#Table(name = "DOSSIER", schema = "ADOP")
public class Dossier extends BaseAutoIncrementModel<Integer> implements BaseModelCode<Integer> {
...
}
Table 2: AlerteDossier
#Entity
#Table(name = "ALERTE_DOSSIER", schema = "ADOP")
public class AlerteDossier extends BaseAutoIncrementModel<Integer> implements BaseModelCode<Integer> {
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "FK_DOSSIER")
private Dossier dossier;
...
}
Table 3: AlerteEnvoi
#Entity
#Table(name = "ALERTE_ENVOI", schema = "ADOP")
public class AlerteEnvoi extends BaseAutoIncrementModel<Integer> implements BaseModelCode<Integer> {
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "FK_ALERTE_DOSSIER")
private AlerteDossier alerteDossier;
...
}
What I have atm:
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<AlerteEnvoi> query = builder.createQuery(AlerteEnvoi.class);
Root<AlerteEnvoi> root = query.from(AlerteEnvoi.class);
query.select(root);
List<Predicate> predicateList = new ArrayList<>();
...
As you can see in AlerteEnvoi the AlerteDossier table is eagerly loaded, though in AlerteDossier the Dossier table is lazily loaded.
I need to create, using the Criteria Api, a select statement for AlerteEnvoi where Dossier would also be loaded within the AlerteDossier entity.
I know how I'd need to fetch the AlerteDossier within the AlerteEnvoi if AlerteDossier would be lazily-loaded (root.fetch("alerteDossier", JoinType.LEFT), I've got no clue how to fetch a sub-entity of a sub-entity though. Anyone can help me with this?
I haven't tested it out yet, but heard from a collegue something like this should be do-able:
Fetch<AlerteEnvoi, AlerteDossier> fetchAlerteDossier = root.fetch("alerteDossier", JoinType.LEFT);
fetchAlerteDossier.fetch("dossier", JoinType.LEFT);
I'll be putting this answer as accepted once I've tested it out.
I have a Person class that has a collection of Contacts. Everything works ok, I get the list of persons with their contacts. However, in log I see that a separate query is made to read collection of every person. That is too bad.
How to make hibernate make a join to read all the data in one query? I use JPA.
This is the person class:
#Entity
#Table(name = "tbl1")
public class PersonItem implements Serializable{
#Id
#Column(name="col1")
private String guid;
.....
#ElementCollection(targetClass = ContactItem.class,fetch=FetchType.EAGER)
#CollectionTable(name="tbl2",joinColumns=#JoinColumn(name="col2"))
private List<ContactItem> contacts;
....
}
This is the contact class
#Embeddable
#Table(name = "tbl2")
public class ContactItem implements Serializable {
#Column(name="col1")
private String guid;
#Column(name="col3")
private String info;
}
This is the way I get the list of persons:
Query query = em.createQuery("Select p from PersonItem p WHERE p.guid IN (:guids)");
query.setParameter("guids", guids);
List<PersonItem> list=query.getResultList();
And this what I see in log (I have three persons in DB):
Hibernate: select personitem0_.col1 as col1_0_, personitem0_.col4 as col2_0_, personitem0_.col2 as col3_0_, personitem0_.col3 as col4_0_ from tbl1 personitem0_ where personitem0_.col1 in (? , ? , ?)
Hibernate: select contacts0_.col2 as col1_1_0_, contacts0_.col1 as col2_1_0_, contacts0_.col3 as col3_1_0_ from tbl2 contacts0_ where contacts0_.col2=?
Hibernate: select contacts0_.col2 as col1_1_0_, contacts0_.col1 as col2_1_0_, contacts0_.col3 as col3_1_0_ from tbl2 contacts0_ where contacts0_.col2=?
Hibernate: select contacts0_.col2 as col1_1_0_, contacts0_.col1 as col2_1_0_, contacts0_.col3 as col3_1_0_ from tbl2 contacts0_ where contacts0_.col2=?
Please, begin from a more simple mapping. Use plural names, and column prefixes.
#Entity
#Table(name = "persons")
public class Person {
#Id
#Column(name = "f_guid")
private String guid;
#OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
private List<Contact> contacts;
}
#Entity
#Table(name = "contacts")
public class Contact {
#Id
#Column(name = "f_guid")
private String guid;
#Column(name = "f_info")
private String info;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "fk_person")
private Person person;
}
Person is associated to contacts by a foreign key fk_person in the contacts table.
Update
Looks like JPQL overrides a default fetching strategy. You need to specify a fetch explicitly
select p from PersonItem p left join fetch p.contacts WHERE p.guid IN (:guids)
If you have duplicates, cause of joins, you can use distinct
select distinct p from PersonItem p left join fetch p.contacts WHERE p.guid IN (:guids)
Try #Fetch on your relation.
Also i would suggest to use #OneToMany relation int this case
#OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
#Fetch(FetchMode.JOIN) //You can use SUBSELECT as well
private List<ContactItem> contacts;
You can read more about fetching strategies here
fetch-“join” = Disable the lazy loading, always load all the collections and entities.
fetch-“select” (default) = Lazy load all the collections and entities.
batch-size=”N” = Fetching up to ‘N’ collections or entities, Not record.
fetch-“subselect” = Group its collection into a sub select statement.
I have 2 entities with #Where annotation. First one is Category;
#Where(clause = "DELETED = '0'")
public class Category extends AbstractEntity
and it has the following relation;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "category")
private Set<SubCategory> subCategories = Sets.newHashSet();
and second entity is SubCategory;
#Where(clause = "DELETED = '0'")
public class SubCategory extends AbstractEntity
and contains corresponding relation;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CATEGORY_ID")
private Category category;
Whenever I call the following Dao method;
#Query(value = "select distinct category from Category category join fetch category.subCategories subcategories")
public List<Category> findAllCategories();
I got the following sql query;
select
distinct category0_.id as id1_3_0_,
subcategor1_.id as id1_16_1_,
category0_.create_time as create2_3_0_,
category0_.create_user as create3_3_0_,
category0_.create_userip as create4_3_0_,
category0_.deleted as deleted5_3_0_,
category0_.update_time as update6_3_0_,
category0_.update_user as update7_3_0_,
category0_.update_userip as update8_3_0_,
category0_.version as version9_3_0_,
category0_.name as name10_3_0_,
subcategor1_.create_time as create2_16_1_,
subcategor1_.create_user as create3_16_1_,
subcategor1_.create_userip as create4_16_1_,
subcategor1_.deleted as deleted5_16_1_,
subcategor1_.update_time as update6_16_1_,
subcategor1_.update_user as update7_16_1_,
subcategor1_.update_userip as update8_16_1_,
subcategor1_.version as version9_16_1_,
subcategor1_.category_id as categor11_16_1_,
subcategor1_.name as name10_16_1_,
subcategor1_.category_id as categor11_3_0__,
subcategor1_.id as id1_16_0__
from
PUBLIC.t_category category0_
inner join
PUBLIC.t_sub_category subcategor1_
on category0_.id=subcategor1_.category_id
where
(
category0_.DELETED = '0'
)
Could you please tell me why the above query lacks
and subcategor1_.DELETED = '0'
inside its where block?
I have just solved a similar problem in my project.
It is possible to put #Where annotation not only on Entity, but on also on your child collection.
According to the javadoc:
Where clause to add to the element Entity or target entity of a collection
In your case, it would be like :
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "category")
#Where(clause = "DELETED = '0'")
private Set<SubCategory> subCategories = Sets.newHashSet();
Please find a similar issues resolved here
I believe thus solution is not as invasive compared to using Hibernate Filters.These filters are disabled by default and operate on Session level, thus enabling them each time new Session opens is extra work especially when your DAO works through abstractions like Spring Data
This is a quick reply;
#Where(clause = "DELETED = '0'")
public class SubCategory extends AbstractEntity
Where will effect when direct query for SubCategry.
To not get deleted sub categories use Hibernate Filters
as exampled on here
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 Pracowniks (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 Grafiks, use join fetch:
from pracownik as p join fetch p.grafiki