I have two classes InvitedPerson and Flight with a one to one relationship with each other. Here is how they are annotated.
public class InvitedTech{
...
#OneToOne(mappedBy="invitedTech", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
public Flight flight;
#OneToOne(mappedBy="invitedTech", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
public Hotel hotel;
...
}
public class Flight{
...
#OneToOne
#JoinColumn(name="invitedTechId", nullable=false)
public InvitedTech invitedTech;
...
}
As you can see Flight is the owner of the relationship and InvitedTech is the other side of this bidirectional relationship. InvitedTech also has a OneToOne relationship with Hotel Now, when I write a simple query to fetch all flights, it triggers three queries in total. 1st which gets me the results, but fires 2 additional queries.
List<Flight> flg = JPA.em().createQuery("SELECT flg from Flight flg").getResultList();
Query that gets all flights (This is the only one that I need)
Query with a join between InvitedTech and Flight
Query with a join between invitedTech and Hotel
Why are query 2&3 being executed even though I have set FetchType=Lazy. I am not accessing Hotel Information. And Flight should not be queries again as the first query returns the data.
After some playing around when I remove mappedBy attribute from both the annotations, those 2 addition queries don't get executed(i.e only 1st gets executed).
Why does the mappedBy attribute cause additional queries to be executed even though FetchType=Lazy. Is there a way to stop this?
I believe this is due to one of Hibernate's idiosyncrasies:
non-optional one-to-one relationships are eagerly loaded regardless of whether they are mapped as Lazy.
The reasoning behind this is that as the engine has to look in the association table anyway - to determine whether it should set the association as a proxy or as null - then it may as well load the associated entity anyway.
I have experienced this myself and as far as I know the only way round it is to mark the relationship with optional=false which tells Hibernate it can always set a proxy.
If the relationship is optional then the only other option seems to be byte code instrumentation.
See also:
https://community.jboss.org/wiki/SomeExplanationsOnLazyLoadingone-to-one
Making a OneToOne-relation lazy
You have not set the association from Flight to InvitedTech lazy. So it loads the InvitedTech associated with the flight.
Since it can't know from the InvitedTech if there exist a Hotel and a Flight associated with the InvitedTech, it can't decide if these fields should be null or should be proxies. So it's forced to execute additional queries to know if a hotel/flight exists for the InvitedTech.
Related
I have read some code describing relationship of two entities on both sides which look like following:
public class Department {
#OneToMany(mappedBy = "department",fetch = FetchType.EAGER , cascade = CascadeType.ALL)
private List<Course> courses = new ArrayList<>();
}
public class Course {
#ManyToOne
private Department department;
}
There are two scenarios: When I use relationship annotation on both sides("on both tables Department and Course ") with One-To-Many relationship and When i only use on one side("only table Derpartment). Scenario is similar for Many-To-Many relationship as well.
My question: Should "fetch = FetchType.EAGER , cascade = CascadeType.ALL" be defined only on one side or both sides in the above mentioned scenarios ?
fetch and cascade options can be defined on both sides. If its defined only on one side that it won't have any impact when the other side object is fetched. e.g. If eager fetch is set for courses in Department class but not in Course class then, if a select query is made on department then, it will fetch all its courses along with it But if a select query is made on course then, it won't fetch its associated department unless explicitly called out in query.
Same goes for cascade option. Thus, its definition on either side depends on the kind of queries which are required to be made. If there are going to be a lot of queries on department which needs all the courses information every time but its not the same for fetching a course then, fetch option should be defined only in Department class for courses.
Bi-directional association is good but with additional update in your code for efficient queries i.e. use JoinColumn with #ManyToOne association so that additional association mapping information between two entities doesn't have to be maintained on code side.
I have a Hibernate entity that is comprised of many other entities that are used within the application. The other entities that make up this MainEntity are joined by using #ManyToOne and #JoinColumn. This MainEntity class has 5 columns (#Column) and 7 #ManyToOne/#JoinColumn entities that are used.
I seem to be running into performance issues when retrieving all of these MainEntity classes. We want to serialize the MainEntity to JSON as well as the other entities that are associated with it. Note that there aren't that many that we are retrieving - less than 30 total.
Below is an example of what the class looks like along with my findAll() method to retrieve these classes. I know that #ManyToOne is EAGER by default, so I'm wondering if there's a better way to get all of these entities that is easier on the system. Thank you in advance.
#Entity(name = "MainEntity")
#Table(name = "main_entity")
public class MainEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
// Other #Columns defined here
#ManyToOne()
#JoinColumn(name = "entity_1_id")
private Entity1 entity1;
#ManyToOne()
#JoinColumn(name = "entity_2_id")
private Entity2 entity2;
#ManyToOne()
#JoinColumn(name = "entity_3_id")
private Entity3 entity3;
// ... and so on, for a total of 7 #ManyToOne() columns
}
Here is the findAll() method that I have:
final List<E> findAllOrdered(Class<E> clazz, Order order) {
final Session session = sessionManager.openNewSession();
try {
return session.createCriteria(clazz)
.addOrder(order)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
} finally {
sessionManager.closeSession(session);
}
}
I found myself having to add the Criteria.DISTINCT_ROOT_ENTITY because we were getting duplicate MainEntity results if a child had multiple associated with it. I suspect this is big part of my performance problem.
If you are retrieving unwanted response and if you want to filter then you may use #JsonIgnore
eg:
#ManyToOne()
#JoinColumn(name = "entity_1_id")
#JsonIgnore
private Entity1 entity1;
Few pointers to consider:
Consider making associations Lazy by default unless you really want to load all the association data and its associations along the parent.
Use JOIN in HQL/criteria based on which association we really want to fetch and the depth of associations.
Or use EntityGraph to decide which associations to be fetch.
Enable show_sql as this show the number of SQLs and the exact SQLs that are getting fired to the DB. This would be a good starting point and subsequently you can tune you associations to LAZY/EAGER, SELECT/JOIN/SUBSELECT based on your use case.
You can run these queries against the DB and see if tuning the query/DB (indexes, partitioning etc) will help reduce the query times.
See if second level cache would help for your use case. Note that second level cache will come with its own complexity and extra overhead and especially if the data is of transactional type and not read-only mostly. With application deployed on nodes maintaining the cache coherence will be another aspect to think about. Need to validate if the extra overhead and complexity is really worth the efficiency outcome of the second level cache.
From an application design perspective, you can also consider and see if you really want to retrieve the MainEntity and the associations in a single request or UI. Instead we could first show the MainEntity with some paging and based on the selection we could fetch the associations for that MainEntity with paging.
Note that, this is not a complete list. But a good starting point and based on your use case you can see which one would fit for you and any other additional techniques.
I have a class Entry which has two fields serving auditing purposes: startAuditAction and endAuditAction. One audit action can affect several entries, therefore the class Entry describes ManyToOne relationships as follows:
public class Entry{
#Id
#Column(nullable = false)
protected String path;
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(nullable = false, name = "start_action_id")
protected AuditAction startAction;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(updatable = true, nullable = true, name = "end_action_id")
protected AuditAction endAction;
}
I want to retrieve instances of Entry based on conditions on the path field and the audit fields. For example to retrieve entries which have not yet been deleted, the HQL would look something like that:
SELECT DISTINCT entry FROM ENTRY_TABLE entry JOIN FETCH entry.startAction startAct LEFT JOIN FETCH entry.endAction endAct WHERE entry.path LIKE myPath and endAct IS NULL
I am using lazy loading together with JOIN FETCH to avoid the N+1 problem while still being able to access the audit fields. However, I have two problems with this:
Firstly, this really does not seem clean to me: if I know I want to access the audit fields (namely the audit actions timestamp), then they should not be lazy loaded. But if I use eager loading I am facing the n+1 problem even if I use JOIN FETCH (and in that case I do not understand why fetch = FetchType.EAGER would ever be useful)...
Secondly, even though I am avoiding the n+1 problem and therefore firing less SQL queries, I get some performance issues for the overall use of my database, probably because of the joins.
What is the proper way to avoid firing additional queries while preserving a good throughput ?
Thanks!
1- Using join fetch is useful when you have FetchType.LAZY in a field that you know you'll need in that specific case whereas using FetchType.EAGER will force that entity to always load the collection independently from the query
(e.g. with your same configuration example you can do multiple query and only when you need the collection use the JOIN FETCH)
2- You probably have problems somewhere else, i doubt the join is what is slowing you down
Today I learned one tutorial where author explained hibernate association one-to-many / many-to-one.
I don't want to write all his code here. So, I try to focus on main...
We have two entities: "Team" and "Player"
In code we have:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="team_id")
private Team team;
and
#OneToMany(mappedBy="team", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Player> players;
The main thing which I interested is type of fetch. So, we inserted one team and some players which are belongs to this team.
My DAO class marked with
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
And now I want to load team entity from database with filled collection of players.
Team team = new Team();
sessionFactory.getCurrentSession().get(team, id);
//and after somewhere in code
team.getPlayers();
At result I will get LazyInitializationException. It's obviously...
We can resolve this problem:
Hibernate.initialize(team.getPlayers());
Or we can can load collection of players using HQL. I mean:
Query query = currentSession().createQuery("from Player p where p.team.id =:id");
query.setParameter("id",key);
team.setPlayers(new HashSet(query.list()));
Is it right solutions? And which of them I should use in real development?
And one more question. After I initialized collection of players (no matter which of solutions I used) I can get one of them. Ok, And in "player" entity field Team will initialize. Why? And this team will be with filled player's collection... we have circular dependencies... This is normal?
LazyInitializationException comes when session is closed and you try to load lazy object from detached Object. Here team is detached object (As session might have closed before this call) and trying to load lazy object players.
And About which approach need to use for this kind of problem, it is up to your requirement. if you call Hibernate.initialize on each proxy, Each call will generate one query.
And with below you are using joint :-
Query query = currentSession().createQuery("from Player p where p.team.id =:id");
this will only require one query, i think you should use this approach if you query a lots of data.
For more information take a look at this link.
I have 2 classes called PurchaseList.java and PurchaseListItems.java
I have to map PurchaseList in PurchaseListItems
PurchaseList.java
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name="pl_id",referencedColumnName="id")
private List<PurchaseListItems> purchaseListItems;
PurchaseListItems.java
#ManyToOne
#JoinColumn(name="pl_id")
private PurchaseList purchaseListId;
Everything is fine but i am getting null in pl_id. Please tell where i am wrong
For some reason mapped by didn't work for me with postgres sql and Hibernate4
Below mapping worked
PurchaseList.java
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name="pl_id",nullable=false)
private List<PurchaseListItems> purchaseListItems;
PurchaseListItems.java
#ManyToOne
#JoinColumn(name="pl_id", nullable=false,insertable=false,updatable=false )
private PurchaseList purchaseListId;
Note: you have to use the Identity or Explicitly mention the Sequence for id columns for postgres.
#GeneratedValue(strategy=GenerationType.IDENTITY)
Your mapping actually defines two independent unidirectional relations. What you want is one bidirectional relation.The following code will establish the bidirectional relation
#OneToMany(cascade = CascadeType.ALL, mappedBy = "purchaseListId")
#JoinColumn(name="pl_id",referencedColumnName="id")
private List<PurchaseListItems> purchaseListItems;
The mappedBy attribute is necessary since there is no way for the provider to automatically determine that the specified relations actually form a single relation. One could use the Java type of the instance member but then what if you have multiple members of the same type. And there are many scenarios where you have two single relations. Example:
OneToMany: User -> ForumThread (the threads created by the user)
ManyToOne: ForumThread -> User (the user who closed the thread. obviously not necessarily the one who started the thread)
These are two independent relations and must be treated as such. You would be quite surprised if your persistence provide just made a bidirectional relation out of that just because the types and multiplicity matched.
Also note that bidirectional relations are not automatically managed by any JPA provider, meaning that the inverse side is not automatically updated/set in your object model and thus not in the db. You have to do that yourself. By the way, in all my projects bidirectional relationships were a pain in the ass and I think it is advisable to avoid them.
The #JoinColumn annotation belongs on the #ManyToOne side of the relationship - but not on the #OneToMany side - remove it from the #OneToMany side.
Cascade is used to cascade DELETE/READ/UPDATE operations..., but it does not automatically populate the ID column on the "child" side of a foreign key. In fact, it doesn't populate the java references to objects on either side of the FK relationship. You need to manually setup relationship data on both sides of bidirectional relationships:
myPurchaseListItem.setPurchaseList(myPurchaseList);
myPurchaseList.setPurchaseListItem(myPurchaseListItem);
From the JPA 2 spec:
Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship. It is the developer’s responsibility to keep the in-memory references held on the owning side and those held on the inverse side consistent with each other when they change. In the case of unidirectional one-to-one and one-to-many relationships, it is the developer’s responsibility to insure (sic) that the semantics of the relationships are adhered to.[29]
It is particularly important to ensure that changes to the inverse side of a relationship result in appropriate updates on the owning side, so as to ensure the changes are not lost when they are synchronized to the database.
for(PurchaseListItems item:purchaseListItemsList)
item.purchaseListId(PurchaseList);
This is what I missed when i am creating an object.
Thnaks for your answers
The jpa specification looks good, but verify you have given valid parent to child relationship in the database. If there is not a reference then it will return null.
try this
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "purchaseListId")
Check if you have populated purchaseListId with valid value (a created PurchaseList instance) when you create a PurchaseListItems value.
It's better to use mappedBy as below code to let many-side to maintian the relationship.
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "purchaseListId")
#JoinColumn(name="pl_id",referencedColumnName="id")
private List<PurchaseListItems> purchaseListItems;