#ManyToMany not all values obtained from DB - java

I have in project user which have authorities. Authorities types stored in database and linked with user as many to many relation.
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "user_authority", joinColumns = #JoinColumn(name = "uauth_user"), inverseJoinColumns = #JoinColumn(name = "uauth_authority"))
private Set<Authority> userAuthorities;
But when I try to get all authorities of selected user I obtain just one of them. Hibernate just get first of them and put it to list, but ignore all other authorities of user.
I already check database and it store this data. Also I found solution with adding one not JPA annotations. It works with #Fetch(FetchMode.SUBSELECT) but I still don't understand what is wrong with it.

The following solution works on any JPA 2.0 - compliant implementation.
Table user has primary key id.
Table authority has primary key id.
Table user_authority has fields user_id, authority_id.
Entity class User
#JoinTable(name = "user_authority",
joinColumns = {#JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {#JoinColumn(name = "authority_id", referencedColumnName = "id")})
#ManyToMany(fetch = FetchType.EAGER)
private Set<Authority> authoritySet;
Entity class Authority
#ManyToMany(mappedBy = "authoritySet", fetch = FetchType.EAGER)
private Set<User> userSet;
The Table user_authority doesn't have an Entity represention in JPA.

Ok problem was in different place.
My fault was that when I tried it with Hibernate annotation and it is just works I started thinking that this is an annotation problem, but actually it was caused with method of obtaining this values.
While refactoring we leae in code one mistake:
return (T) criteria.setMaxResults(1).uniqueResult();
He we set maximal count of results as 1 and in our case it converted to SQL as
SELECT * FROM user OUTER JOIN user_authority ON usr_id = uauth_user INNER JOIN authority ON uauth_authority = auth_id LIMIT 1
This limit removes all authorities, and leave just first authority from first line. But when we specify Hibernate FetchMode as SUBSELECT. It execute this get in two separate SQL queries. In which just main have limit.

Related

Problem with ManyToMany relations in spring data. It changed my table

I had a db with tables SPEC and PARTS.Also I had a table for MANY TO MANY relations. In my project I used spring jdbs template and all works good. Then I decide to change jdbc on SPring data jpa.
My Entities:
#Entity
#Table(name = "PARTS")
public class PartsJpa {
#Id
private int id;
#Column(name = "NAME")
private String name;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "ID_EXPORT", unique = false, nullable = false, updatable = true)
private ExportJpa exportJpa;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "ID_TYPE", unique = false, nullable = false, updatable = true)
private TypesJpa typesJpa;
#Column(name = "DESCRIPTION")
private String description;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name="SPEC_PARTS",
joinColumns = #JoinColumn(name="ID_SPEC", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="ID_PARTS", referencedColumnName="id")
)
private Set<SpecJpa> specJpa;
////////
}
And Spec:
#Entity
#Table(name = "SPEC")
public class SpecJpa {
#Id
private int id;
#Column(name = "NAME")
private String name;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "Creator_ID", unique = false, nullable = false, updatable = true)
private UsersJpa usersJpa;
#Column(name = "DESCRIPTION")
private String description;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name="SPEC_PARTS",
joinColumns = #JoinColumn(name="ID_SPEC", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="ID_PARTS", referencedColumnName="id")
)
private Set<PartsJpa> partsJpa;
////////////////
}
I don't show getters and setters.
It works, but when I start a programm, something in my table was changed and now I can't add in table spec_parts values like(1,3)(1,2).
Mistake:
FK_123: PUBLIC.SPEC_PARTS FOREIGN KEY(ID_PARTS) REFERENCES PUBLIC.SPEC(ID) (3)" Referential integrity constraint violation: "FK_123: PUBLIC.SPEC_PARTS FOREIGN KEY(ID_PARTS) REFERENCES PUBLIC.SPEC(ID) (3)"; SQL statement: INSERT INTO "PUBLIC"."SPEC_PARTS"("ID_SPEC","ID_PARTS")VALUES(?,?)
Maybe I have mistake with creating relations between spec and parts? What problem it can be?
data in spec
ID NAME CREATOR_ID DESCRIPTION CHANGER_ID
1 pc 1 description 1
2 pc2 2 description2 2
data in parts
ID ▼ NAME ID_EXPORT ID_TYPE DESCRIPTION
1 intel core i5 1 1 d1
2 intel core i7 1 1 d2
3 ddr3 2 2 d3
4 ddr4 2 2 d4
5 asus 3 3 d5
data in spec_parts now:
ID_SPEC ID_PARTS
1 1
2 2
so I can't add 1,3 or 2,4
I find a problem, spring date change something and now in table SPEC_PARTS ID_SPEC mapping on PARTS.ID. Why?
As you are using ManyToMany relation, there is a mapping table created named SPEC_PARTS which have referenced columns ID_SPEC and ID_PARTS.These columns value come from SPEC.ID and PARTS.ID. So you can't insert in SPEC_PARTS without creating referenced value because you are trying to do foreign key constraint violation.
Suppose if there is a row in SPEC with id value 1 and there is a row in PARTS with id value 2. Then you can insert in SPEC_PARTS with value like (1,2).
So, first, add data in SPEC and PARTS then map them in SPEC_PARTS.
And you can remove #JoinTable from one side, you don't need to define it both side.
Update:
Problem is SpecJpa class relation. Here you are using SPEC_PARTS.ID_SPEC as foriegn key for PARTS.ID and SPEC_PARTS.ID_PARTS as foriegn key for SPEC.ID which is fully reversed what you do in PartsJpa class.
#JoinTable(name="SPEC_PARTS",
joinColumns = #JoinColumn(name="ID_SPEC", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="ID_PARTS", referencedColumnName="id")
)
That's why this error say
SPEC_PARTS FOREIGN KEY(ID_PARTS) REFERENCES PUBLIC.SPEC(ID) (3)";
There is no SPEC.ID value 3 exist in the database.
Solution:
Remove #JoinTable from SpecJpa class as you don't need to specify both side.
And remove the wrong relation of the foreign key from database also.

#JoinColumn gives error "column with logical name ID not found" in Hibernate 4

I am having below annotation on column in my entity class.
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "INQUIRYID", referencedColumnName="ID", updatable=false, insertable=false)
private MyTable myInquiry;
It was giving below error on runtime.
column with logical name ID not found in entity class
As the referenced column is a primary key, I removed the referencedColumnName attribute and updated to below
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "INQUIRYID", updatable=false, insertable=false)
private MyTable myInquiry;
This works perfectly with Hibernate 5.3 but as soon as I go to hibernate 4 , I see some anomalies.
In hibernate 5 I get this issue only with columns which are referring some ID(PK) of another class. However, in hibernate 4 I see this error for non-pk columns as well.
I start to get the same error for columns which are referring non primary keys.
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "AB", referencedColumnName = "AB")
private MyTable someData;
Above code gives me error in hibernate 4
Column with logical name AB not found in entity class.
Here, AB is a non primary key column .So I can't remove referencedColumnName attribute.
Is it purely because of hibernate version or there is a different reason for such behavior ?
Referred this : Similar Issue
There is a bug for hibernate 4.1.7
A workaround for this issue is surrounding the column name with gave accents.
Unable to find column with logical name: id in
org.hibernate.mapping.Table(template) and its related supertables and
secondary tables
#ManyToOne #JoinColumnsOrFormulas({ #JoinColumnOrFormula(column =
#JoinColumn(name = "template", referencedColumnName = "id")),
#JoinColumnOrFormula(formula = #JoinFormula(value = "'custom'",
referencedColumnName = "type")) }) This is caused by identifying the
column names within the logicalToPhysical map of
TableColumnNameBinding. Within this map the column names are
surrounded by grave accents (`id`) while the check do a lookup to the
map with plain column name (id).
A workaround for this issue is surrounding the column name with gave
accents.
#ManyToOne #JoinColumnsOrFormulas({ #JoinColumnOrFormula(column =
#JoinColumn(name = "template", referencedColumnName = "`id`")),
#JoinColumnOrFormula(formula = #JoinFormula(value = "'custom'",
referencedColumnName = "`type`")) })

How to perform soft deletes on an association mapping table in Hibernate?

So although I personally hate soft deletes, im working in a project for which every table must only soft delete. Im not sure how to handle soft deletes on an association table, the field for which looks like this:
#ManyToMany(targetEntity = AdvertisementVendor.class, fetch = FetchType.EAGER)
#JoinTable(name = "advertisement_version_advertisement_vendor_association",
joinColumns = #JoinColumn(name = "advertisement_version_id"),
inverseJoinColumns = #JoinColumn(name = "advertisement_vendor_id"))
private Set<AdvertisementVendor> _advertisement_vendors = new HashSet<>();
I've seen how to do soft deletes, but I'm not sure how I would apply that to the association table.
UPDATE:
Taking Dragan Bozanovic's advice I updated my column to:
#ManyToMany(targetEntity = AdvertisementVendor.class, fetch = FetchType.EAGER)
#JoinTable(name = "advertisement_version_advertisement_vendor_association",
joinColumns = #JoinColumn(name = "advertisement_version_id"),
inverseJoinColumns = #JoinColumn(name = "advertisement_vendor_id"))
#WhereJoinTable(clause = "is_deleted = 0")
#SQLDelete(sql = "UPDATE advertisement_version_advertisement_vendor_association SET is_deleted = 1 WHERE advertisement_version_id = ? AND advertisement_vendor_id = ?", check = ResultCheckStyle.COUNT)
#SQLInsert(sql = "INSERT INTO advertisement_version_advertisement_vendor_association " +
"(advertisement_version_id, advertisement_vendor_id, is_deleted) VALUES(?, ?, 0) " +
"ON DUPLICATE KEY UPDATE is_deleted = 0")
private Set<AdvertisementVendor> _advertisement_vendors = new HashSet<>();
But this doesnt seem to be working. It seems to ignore #SQLDelete and just removes the mapping.
UPDATE 2:
Ignore the first update, it had to do with different code. The above example works as is.
You can use #WhereJoinTable for filtering conditions on join tables:
Where clause to add to the collection join table. The clause is
written in SQL. Just as with Where, a common use case is for
implementing soft-deletes.
I had a similar problem, and while your solution does work, I also had to add an #SQLDeleteAll annotation in addition to #SQLDelete.
The problem I had is it was still calling the default delete statement when I cleared all entries from the HashSet or deleted the parent object.
Apologies if my terminology is a little off, I'm still pretty new to Hibernate.

When use the JPA innerJoin, How can i change 'and' to 'or'?

When mapping two or more columns in innerjoin there is a map to the conditions and
Can I change or a condition?
Parent table
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<KeyboxDept> keyboxDept;
Child table
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "KEY_TARGET_ID", referencedColumnName = "DEPT_ID", insertable = false, updatable = false),
#JoinColumn(name = "KEY_TARGET_UPPER_ID", referencedColumnName = "DEPT_ID", insertable = false, updatable = false)
})
private User user;
Query is made
select
user0_.user_id as user_id1_3_,
user0_.dept_id as dept_id2_3_,
user0_.posi_id as posi_id3_3_
from
cm_user user0_
inner join
cm_keybox_dept keyboxdept2_
on user0_.dept_id=keyboxdept2_.key_target_id
and user0_.dept_id=keyboxdept2_.key_target_upper_id
where
user0_.user_id=? limit ?
Can i switch and -> or ???
I am not sure about JPA but In Hibernate Using Criteria we can do this....
Criteria criteria = session.createCriteria(persistentClass);
criteria.createCriteria("propertyName", Criteria.LEFT_JOIN);
You have cascade = CascadeType.ALL in entity definition. That means, The operations that must be cascaded to the target of the association. So the target (KeyboxDept in your code) must exist. If you remove it, means no operations being cascaded, I think the generated sql will have no inner.
If your search criteria is not a foreign key matching to the joined table key then you cannot use this syntax because there is obviously an AND relationship between the separate column parts (#JoinColumn elements) of the foreign key. This is why the generated native SQL contains the AND. If you need the OR, you need to initialize that member with a separate JPQL query which contains the OR and you do not need the annotation #ManyToOne.

Hibernate: Unable to eagerly fetch child collection of a child collection

I have a Session class, which has a mapped collection of Photo objects:
#OneToMany(fetch = FetchType.EAGER)
#Fetch(FetchMode.SUBSELECT)
#JoinColumn(name = "sessionId", insertable = false, updatable = false)
private SortedSet<Photo> photos = new TreeSet<>();
Each Photo in turn has a collection of Comment objects, which is designated as being FetchType.LAZY (because I don't always want them):
#OneToMany(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
#BatchSize(size=20)
#Fetch(FetchMode.SUBSELECT)
#JoinColumn(name = "photoId", insertable = false, updatable = false)
private SortedSet<Comment> comments = new TreeSet<>();
In my query for Sessions, I'd like to be able to programmatically decide, on-the-fly, whether to include the Comments or not. I've tried (among other variations):
Criteria criteria = hibSession.createCriteria(Session.class, "s")
.createAlias("photos", "p")
.setFetchMode("p.comments", FetchMode.JOIN);
But that doesn't do it. Calling photo.getComments() on any of the returned Photo sub-objects throws a LazyInitializationException.
If I (still within the scope of the original Hibernate session) iterate over all the Sessions, and within that all the Photos, and call photo.getComments().size(), that will fetch the Comments (in batches, as specified).
But is there any way to tell the initial query to just eagerly get all the Comments the first time around, without the need to iterate afterwards?
Thanks.
It's probably well known Hibernate bug HHH-3524, setFetchMode doesn't work as expected in Criteria queries. It was closed as stale issue, but some users report it for Hibernate versions 4.x.x.
To fix that you can use HQL since it works properly:
session.createQuery("SELECT s FROM PhotoSession s " +
"JOIN FETCH s.photos p " +
"JOIN FETCH p.comments");
Or use workaround solution with createCriteria(associationPath, JoinType.LEFT_OUTER_JOIN):
Criteria criteria = session.createCriteria(PhotoSession.class, "s");
criteria.createAlias("photos", "p");
criteria.createCriteria("p.comments", "c", JoinType.LEFT_OUTER_JOIN);
criteria.setFetchMode("c", FetchMode.JOIN);

Categories