I am using Hibernate in a Java project to connect to the database. I have the following classes:
#Entity
#Table(name = "a")
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
}
#Entity
#Table(name = "b")
public class B extends A {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "c_id", nullable = false)
private C c;
}
#Entity
#Table(name = "c")
public class C {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
}
I am trying to write a query over A that will eagerly fetch C inside B. I tried to do:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<A> criteria = builder.createQuery(A.class);
Root<Pin> root = criteria.from(A.class);
criteria.select(root);
builder.treat(root, B.class).fetch("c", JoinType.LEFT);
But it won't perform the fetch. Oddly enough, I was able to do the following successfully to do a left join:
Join c = builder.treat(root, B.class).join("c", JoinType.LEFT);
Any ideas what I am doing wrong?
If you have a field set FetchType.LAZY and you want it to be eager fetched in one spefic query you have two options:
1.
The simplest way is just query normally and iterate over the result to force hibernate to fetch the nested fields.
List<Class> result = session.createCriteria(persistentClass).list();
for(Class c : result)
c.getLazyField();
2. The hard way, if you have some special requirement where you must run just one query on DB level you will need to get a cursos and fecth every field MANUALLY.
As you set the field to be lazy, doesn't matter if hibernate sees it on the resultset, it will simple ignore since it was annotated to be.
Related
I have an entity class with a where condition that pulls the records with ACTIVE = true flag. I have an additional column which is referring to the same class and i want to pull ACTIVE = true or ACTIVE = false records during query execution. Is there a way to override entity's #Where clause when calling the "PARENT_INSTANCE_ID" records?
#Entity
#Table(name = "MY_TABLE")
#Where(clause = "ACTIVE = true")
public class MyTable {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "INSTANCE_ID")
private Long id;
#ManyToOne(fetch = LAZY)
#JoinColumn(name = "PARENT_INSTANCE_ID")
private MyTable parent;
.....
.....
}
So I have two entities:
#Getter
#Setter
#Entity
#Table(name = "MY_TABLE")
public class MyTable {
#Id
#Column(nullable = false, length = 18)
#SequenceGenerator(name = "MY_TABLE_seq", sequenceName = "MY_TABLE_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_TABLE_seq")
private long id;
#OneToOne(mappedBy = "myTable")
private MyTableView myTableView;
}
And an Immutable entity (the reason for this is that it is a database view):
#Entity
#Getter
#Immutable
#Table(name = "MY_TABLE_VIEW")
public class MyTableView {
#Id
#Column(name = "ID", nullable = false, length = 18)
private Long id;
#OneToOne
#MapsId
#JoinColumn(name = "id")
private MyTable myTable;
}
Updating and creating the MyTable works without a problem. The problem start when I try to remove the MyTable. I am using the repository for that:
public interface MyTableRepository extends CrudRepository<MyTable,Long> {
}
In the service I am using:
public void deleteMyTable(Long id){
/*fetch the my table enity*/
myTableRepository.delete(myTable);
}
Nothing happens. No exception nothing at all. What I have tried is changing the #OneToOne mapping. With different cascade:
#OneToOne(mappedBy = "myTable",cascade = CascadeType.ALL)
#OneToOne(mappedBy = "myTable",cascade = CascadeType.DETACH)
#OneToOne(mappedBy = "myTable",cascade = CascadeType.MERGE)
#OneToOne(mappedBy = "myTable",cascade = CascadeType.REFRESH)
#OneToOne(mappedBy = "myTable",cascade = CascadeType.REMOVE)
#OneToOne(mappedBy = "myTable",cascade = CascadeType.PERSIST)
ALL,MERGE and REMOVE throws and exception as I can not delete from a
view
DETACH,REFRESH and PERSIST does nothing but the MyTable entity is not
removed
Does anyone have an idea how to resolve this problem?
As indicated in the question comments, I suggested you to try creating some kind of #PreRemove hook in order to avoid the problem.
Because it makes perfect sense according to how the relationship between your entities is defined.
But if you think about that, you are dealing with a view, with a read-only entity: in my opinion, it makes more sense to invert the relationship and make MyTable the owner. In addition probably it will solve the issue.
Please, consider define you relationship with MyTableView in MyTable like this:
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "id")
private MyTableView myTableView;
In MyTableView, simplify your relationship with MyTable in the following way:
#OneToOne(mappedBy = "myTableView")
private MyTable myTable;
This is probably caused by the constraint on the mapping.
An alternative way to remove "MyTableView" instance when deleting "MyTable" is to set "orphanRemoval = true". I think this is better for a double OneToOne mapping.
there are some links that (i hope) may helps you :
Hibernate one to one mapping. Delete row from dependent table
How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause
When migrating from standard JPA (EclipseLink) to hibernate, tests are failing due to improper number of child records and/or invalid types for child objects.
I think the issue is the SQL generated by hibernate is not using the discriminator column in the where clause on an InheritanceType.SINGLE_TABLE relationship.
Any suggestions on what to change in the mappings?
Thanks in advance,
Timothy
Environment
postgres 9.6.17
spring boot / JPA 2.4.0
postgres mvn dependency 42.2.18
Domain background
A DcMotor may have up to 2 sets of wires. Represented in the entity each in its own List. These wires are of either ARM or EQ type. Since the attributes on the wires are the same, a single table was chosen by the DBA with a discriminator column named coil_type with values of either ARM or EQ.
Class definitions
Parent Entity
#Entity
#Table(name = "dc_motor")
public class DcMotor implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Version
private Integer version;
//other direct fields
#OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "motor_id", referencedColumnName = "id", nullable = false)
#OrderColumn(name = "idx")
private List<WireArm> armWires;
#OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "motor_id", referencedColumnName = "id", nullable = false)
#OrderColumn(name = "idx")
private List<WireEq> eqWires;
Abstract base class for WireArm and WireEq
#Entity
#Table(name = "dc_wire")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "coil_type", length = 10, discriminatorType = DiscriminatorType.STRING)
public abstract class DcWire implements IDcWire {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// other direct fields
// discriminator column coil_type is not explicitly listed as a field
Concrete child class
#Entity
#DiscriminatorValue(value = "ARM")
public class WireArm extends DcWire implements IDcWire {
// just constructors
}
#Entity
#DiscriminatorValue(value = "EQ")
public class WireEq extends DcWire implements IDcWire {
// just constructors
}
SQL generated
select /*all fields*/ from dc_motor dcmotor0_ where dcmotor0_.id=1;
select /* all fields EXCEPT coil_type*/ from dc_wire armwires0_ where armwires0_.motor_id=1;
select /* all fields EXCEPT coil_type*/ from dc_wire eqwires0_ where eqwires0_.motor_id=1;
I think this can be solved by using org.hibernate.annotations.DiscriminatorOptions(force = true).
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.
I am having an issue with generated SQL's from a model we built using JPA (TopLink)
We have the following
#Entity
#Table(name = "T_TEST_A")
#Access(AccessType.FIELD)
public class TTestA implements Serializable {
#Id
#Column(name = "A_ID")
private String id;
#OneToOne
#PrimaryKeyJoinColumn
private D detail;
#OneToMany()
#JoinTable(name = "T_TEST_JOIN", joinColumns = #JoinColumn(name = "TABLE_FK"), inverseJoinColumns = #JoinColumn(name = "B_ID"))
private List<B> childrens;
...
}
#Entity
#Table(name = "T_TEST_B")
#Access(AccessType.FIELD)
public class TTestB implements Serializable {
#Id
#Column(name = "B_ID")
private String id;
#OneToOne
#PrimaryKeyJoinColumn
private D detail;
...
}
#Entity
#Table(name = "T_TEST_D")
#Access(AccessType.FIELD)
public class D implements Serializable {
#Id
#Column(name = "D_ID")
private String id;
#OneToOne
#PrimaryKeyJoinColumn
private M moreDetail;
...
}
It's basically an one to many using a 3 tables relation. Using the Criteria API, I am able to get the first level and all the One-To-One relations (cascading) and children from A, ie A=>D=>M, in a single SQL using fetch's, but I can't get the children B=>D=>M to act the same.
I end up with a SQL query which gets A, D, M and B, but then multiple queries to get B=>D=>M.
Here is what I do:
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<A> c = cb.createQuery(A.class);
final Root<A> a = c.from(A.class);
a.fetch(A_.details).fetch(D_.modeDetails);
a.fetch(A_.childrens);
...
Is it possible to "compound" the calls for the children also?
After much fiddling, I noticed I had another issue also which was that the query would return duplicates.
So I ended up using a.join(A_.childrens, JoinType.LEFT).fetch(B_.details)
And using the query hint
query.setHint(QueryHints.FETCH, "t1.childrens")
I managed to eliminate the duplicates and fetch the deeper level.