Hibernate eager loading not fetching all child rows - java

Hibernate version 4.3.10
I have parent/child relationship as described in the example. There are occasions when we expect only one row to be returned when querying for Provider. In this case, we limit the criteria by calling setMaxResults method to 1.
Dump of SQL revealed that hibernate makes outer join calls which ends up returning more than one row, but because of limit set on criteria, only first child row is read from database.
#Entity
#Table(name = "F_PROVIDER")
public class Provider {
#OneToMany(cascade = CascadeType.ALL, mappedBy = "provider", orphanRemoval = true, fetch = FetchType.EAGER)
private final Set<CredentialFieldDefinition> credentialFieldDefinitionList;
}
#Entity
#Table(name = "F_CRED_FIELDS", uniqueConstraints = { #UniqueConstraint(columnNames = { "name", "provider_id" }) })
public class CredentialFieldDefinition {
#ManyToOne(targetEntity = Provider.class, optional = false)
#JoinColumn(name = "PROVIDER_ID", nullable = false, unique = false)
private Provider provider;
}
How do I convince to return me full child set when I am reading only row?

You can try using SUBSELECT fetch mode:
#OneToMany(cascade = CascadeType.ALL, mappedBy = "provider", orphanRemoval = true, fetch = FetchType.EAGER)
#Fetch(FetchMode.SUBSELECT)
private final Set<CredentialFieldDefinition> credentialFieldDefinitionList;
This way credentialFieldDefinitionList will be initialized in a separate query.

Related

#EntityGraph unloads related entities ignoring #Where annotation

I am using soft delete in my project. I need to unload a lot of related entities. I am using #EntityGraph with multiple entities at the same time - entityA.EntityB.EntityC, this does not work on related entities.
Each entity has the #Where annotation. I've tried using #Where and #WhereJoinColumn entities on the field. It gave no results
#Entity
#Where(clause = "field is null")
public class EntityA {
#OneToOne(mappedBy = "entityA", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
#PrimaryKeyJoinColumn
private EntityB entityB;
#Entity
#Where(clause = "field is null")
public class EntityB {
#MapsId
#OneToOne(fetch = FetchType.LAZY)
private EntityA entityA;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", referencedColumnName = "id", nullable = false)
private EntityC entityC;
#Entity
#Where(clause = "field is null")
public class EntityC {
#OneToMany(mappedBy = "EntityB")
#Audited(targetAuditMode = NOT_AUDITED)
private Set<EntityB> set = new HashSet<>();
public interface EntityARepository extends JpaRepository<EntityA, Integer> {
#EntityGraph(attributePaths = {"entityB.entityC"})
Optional<EntityA> findById(Integer id);
I want Hibernate to return me a query like
SELECT * FROM EntityA
LEFT JOIN EntityB ON EntityA.id = EntityB.id
AND EntityB.field is null
LEFT JOIN EntityC ON EntityB.id = EntityC.id
AND EntityC.field is null
WHERE EntityA.id = ? AND EntityA.field is null
But it comes back to me
SELECT * FROM EntityA
LEFT JOIN EntityB ON EntityA.id = EntityB.id
LEFT JOIN EntityC ON EntityB.id = EntityC.id
AND EntityC.field is null
WHERE EntityA.id = ? AND EntityA.field is null
How do I get Hibernate to see all my #Where annotations when unloading many related entities. I wrote a query in hql, but it is too cumbersome.
Thanks

Hibernate/JPA unidirectional OneToMany with join condition on constant value in source table

I want to use Hibernate annotations to represent a unidirectional one-to-many relationship using a join. I want an added condition on the join so it only happens when a column in the source table (the "one") is equal to a constant value. For example.
SELECT *
FROM buildings b
LEFT JOIN building_floors bf on bf.building_id = b.id AND b.type = 'OFFICE'
I want to represent the b.type = 'OFFICE' part of that query.
My question is quite similar to this one, except I have a condition on the source table. JPA/Hibernate Join On Constant Value
The Java entities look like this:
#Entity
#Table(name = "buildings")
public class Building {
#Id
#Column(name = "id")
private int id;
#Column(name = "type")
private String type;
#OneToMany(mappedBy = "buildingId",
fetch = FetchType.EAGER,
cascade = {CascadeType.ALL},
orphanRemoval = true)
#Fetch(FetchMode.JOIN)
// buildings.type = 'OFFICE' ????
private Set<BuildingFloors> buildingFloors;
// getters/setters
}
#Entity
#Table(name = "building_floors")
public class BuildingFloor {
#Id
#Column(name = "building_id")
private int buildingId;
#Id
#Column(name = "floor_id")
private int floorId;
#Column(name = "description")
private String description;
// getters/setters
}
I've tried a few things where I have that placeholder comment:
#Where annotation
This doesn't work since that applies to the target entity.
#JoinColumns annotation
#JoinColumns({
#JoinColumn(name = "building_id", referencedColumnName = "id"),
#JoinColumn(name = "'OFFICE'", referencedColumnName = "type")
})
This doesn't work because I get the following error (simplified for clarity): Syntax error in SQL statement "SELECT * FROM buildings b JOIN building_floors bf on bf.building_id = b.id AND bf.'OFFICE' = b.type"
A different #JoinColumns annotation
#JoinColumns({
#JoinColumn(name = "building_id", referencedColumnName = "id"),
#JoinColumn(name = "buildings.type", referencedColumnName = "'OFFICE'")
})
This doesn't work because when using a unidirectional OneToMany relationship, the referencedColumnName is from the source table. So I get the error: org.hibernate.MappingException: Unable to find column with logical name: 'OFFICE' in buildings
Thanks in advance!
Why not use inheritance ? (I use it with JPA, I never use hibernate directly)
#Entity
#Inheritance
#Table(name = "buildings")
#DiscriminatorColumn(name="type")
public class Building {
#Id
#Column(name = "id")
private int id;
#Column(name = "type")
private String type;
}
And :
#Entity
#DiscriminatorValue("OFFICE")
public class Office extends Building {
#OneToMany(mappedBy = "buildingId",
fetch = FetchType.EAGER,
cascade = {CascadeType.ALL},
orphanRemoval = true)
private Set<BuildingFloors> buildingFloors;
}
Create database View with the following select:
SELECT bf.* FROM building_floors bf JOIN buildings b on bf.building_id = b.id AND b.type = 'OFFICE'
Map it to a class OfficeBuildingFloors as an ordinary entity and then use #OneToMany for it in Building class.
Of course, you won't be able to modify such collection and to avoid any exception you can use #Immutable on OfficeBuildingFloors.
In my opinion you should create a specific query to achieve your goals, rather than put specific annotations with constant parameter. I'm not see you mention another frameworks besides Hibernate so I would give some example with Hibernate. In your Building class your unidirectional mappings look like this:
#OneToMany(fetch = FetchType.Lazy, cascade = {CascadeType.ALL}, orphanRemoval = true)
#JoinTable(name = "building_floors", joinColumns = #JoinColumn(name = "id"), inverseJoinColumns = #JoinColumn(name = "building_id")
private Set<BuildingFloor> buildingFloors;
Then you can fetch your data using TypedQuery like this.
TypedQuery<Customer> query = getEntityManager().createNamedQuery("select b from building b inner join fetch b.buildingFloors where b.type = 'OFFICE'", Building.class);
List<Building> result = query.getResultList();
My solutions is not Hibernate specific, actually you could perform this with simple JPA. Hope this can help you to achieve your goals.
As you want filter source table you could use #Loader annotation
#Entity
#Table(name = "buildings")
#Loader(namedQuery = "building")
#NamedNativeQuery(name="building",
query="SELECT * FROM buildings b"
+ " LEFT JOIN building_floors bf on bf.building_id = b.id"
+ " WHERE b.type = 'OFFICE' AND b.id = ?",
resultClass = Building.class)
class Building
Approach with view in DB would be better and more clearly, if it could be used inside DB also. Otherwise rename Building to something which explicitly represent filtering.
Another approaches to mention: #Filter, #FilterDef.

JPA query left join without loading the joined entity field

I have 3 JPA entities such as:
#Entity
public class Link implements {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "network", referencedColumnName = "id")
private Network network;
//...
}
#Entity
public class Network implements LinkOwner {
#OneToMany(mappedBy = "network")
#Cascade(value = { CascadeType.ALL })
private Set<Link> links;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "project", referencedColumnName = "id", nullable = false)
private Project Network.project;
//...
}
#Entity
public class Project {
#OneToMany(mappedBy = "project", orphanRemoval = true)
#Cascade(value = { CascadeType.ALL })
#Fetch(FetchMode.SELECT)
private Set<Network> networks;
}
And I do a JPA query such as:
SELECT l FROM Link l left join fetch l.subnetwork sann
where sann.project.id = :projectId
and it generates a SQL query similar to:
select * from RMT6.link, SUBNETWORK where link.subnetwork = SUBNETWORK.id
and SUBNETWORK.project=?
How can I trigger a JPQL query that selects only the fields of the first entity and exclude those of the second one?
What do I need to change in my JPQL query?
Base on your entity relationship, you don't need to use JOIN query, I think.
SELECT * FROM LINK l WHERE l.network.project.id = :projectId

Hibernate - multiple many to many associations - cannot simultaneously fetch multiple bags

I'm trying to map two many to many associations in cascade. I have three classes: User, Usergroup and Permission. The first one has a many to many association to the second one while the second one has a many to many association to the third one.
I'm using hibernate 4.2.0
#Entity
#Table(name = "user")
public class User implements Serializable {
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = org.weedea.bidupsys.user.logic.model.UserGroup.class)
#JoinTable(name = "UserGroupUser", joinColumns = { #JoinColumn(name = "userId") }, inverseJoinColumns = { #JoinColumn(name = "userGroupId") })
private List<UserGroup> userGroupList = null;
}
#Entity
#Table(name = "userGroup")
public class UserGroup implements Serializable {
#ManyToMany(fetch = FetchType.EAGER, targetEntity = org.weedea.bidupsys.user.logic.model.Permission.class, cascade = { CascadeType.ALL })
#JoinTable(name = "UserGroupPermission", joinColumns = { #JoinColumn(name = "userGroupId") }, inverseJoinColumns = { #JoinColumn(name = "permissionId") })
private List<Permission> permissionList = null;
}
With this configuration I get an error, because I try to load simultaneously two eager collections:
javax.servlet.ServletException: cannot simultaneously fetch multiple bags
javax.faces.webapp.FacesServlet.service(FacesServlet.java:229)
If I put fetch = FetchType.LAZY on the second collection, I get another error:
failed to lazily initialize a collection of role: org.weedea.bidupsys.user.logic.model.UserGroup.permissionList, could not initialize proxy - no Session
How could I map this two many to many associations? Thanks for help!
Short answer is you need to map them as java.util.Sets.
Here's a nice blog post explaining the issue: Hibernate Exception - Simultaneously Fetch Multiple Bags

JPA many to many self referencing relation with additional column

I am working with JPA and use Hibernate as a provider to my SQL Server database.
I need a many-to-many self referencing relation that has an additional column or even more additional columns.
That is my current code. I am getting exceptions by Hibernate:
#Entity
public class Person {
#OneToMany(cascade = CascadeType.ALL, mappedBy = "person", fetch = FetchType.EAGER)
private Set<Relation> relations;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "relPerson", fetch = FetchType.EAGER)
private Set<Relation> inverseRelations;
}
#Entity
public class Relation implements Serializable {
#Id
#ManyToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "PersonID", referencedColumnName = "id")
private Person person;
#Id
#ManyToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER)
#PrimaryKeyJoinColumn(name = "RelPersonId", referencedColumnName = "id")
private Person relPerson;
}
During runtime i get an exception from hibernate:
org.hibernate.TransientObjectException: object references an unsaved transient instance
Is there any way to implement this a little bit more intelligent and nicely?? Without getting that exception.
Thanks,
ihrigb
If an object not associated with a Hibernate Session, the object will be Transient.
An instance of Relation list may be Transient(Normally, There is no identifier value for that instance) when you save Person.
Here is better way to understand object state.

Categories

Resources