NamedQuery returning object instead of column - jpa

Hi I have a namedquery defined as below but when I execute it it retunrns me the whole object rather than just the fields that I have requested. Is there something that I am missing when I only want to return just a column of that object. Thanks in advance
#NamedQueries ({
#NamedQuery(
name="findSubmissionForSubmissionRowUniqueBankId",
query="SELECT o.submission FROM SubmissionRow o WHERE o.uniqueBankId = :uniqueBankId",
hints={#QueryHint(name=QueryHints.CACHE_USAGE, value=CacheUsage.CheckCacheThenDatabase),
#QueryHint(name=QueryHints.QUERY_RESULTS_CACHE_SIZE, value="1000"),
#QueryHint(name=QueryHints.QUERY_RESULTS_CACHE_EXPIRY, value="18000")
})
})
The sql that it excecutes for this query is
EJBQueryImpl(ReadObjectQuery(name="findSubmissionForSubmissionRowUniqueBankId" referenceClass=SubmissionRow sql="SELECT ID, ARCHIVE_BANK_ID, EXTERNAL_SOURCE_DETAILS,UNIQUE_BANK_ID, SUBMISSION_ID FROM FE_TEST.SUBMISSION_ROW WHERE (UNIQUE_BANK_ID = ?)"))
I have defined the join as folllows
#ManyToOne
#JoinColumn(name = "SUBMISSION_ID", referencedColumnName = "ID")
private Submission submission;

Your hints do not make sense,
#QueryHint(name=QueryHints.CACHE_USAGE, value=CacheUsage.CheckCacheThenDatabase),
#QueryHint(name=QueryHints.QUERY_RESULTS_CACHE_SIZE, value="1000"),
#QueryHint(name=QueryHints.QUERY_RESULTS_CACHE_EXPIRY, value="18000")
You seem to think you are using query caching, but are not. CACHE_USAGE does not enable query caching, but in-memory querying (searches the entire cache for the object).
To enable the query cache use, QueryHints.QUERY_RESULTS_CACHE = true.
Remove CACHE_USAGE. CACHE_USAGE in-memory querying is only supported with the whole objects, it does not support selecting parts. If you want to use in-memory querying, just query the whole object, and then access the part you want.

Related

JPQL query delete not accept a declared JOIN?

I'm trying to understand why the Hibernate not accepts this follow JPQL:
#Modifying
#Query("delete from Order order JOIN order.credit credit WHERE credit.id IN ?1")
void deleteWithListaIds(List<Long> ids);
The error that I receive is:
Caused by: java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:46)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
But accepts this:
#Modifying
#Query("delete from Order order WHERE order.credit.id IN ?1")
void deleteWithListaIds(List<Long> ids);
The entity Order (the entity Credit does not map the Orders):
#Entity
public class Order {
#Id
#Setter
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
#SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE, allocationSize = 1)
#Column(name = "id", nullable = false)
private Long id;
#JoinColumn(name = "credit_id", foreignKey = #ForeignKey(name = "fk_order_credit"))
#ManyToOne(fetch = FetchType.LAZY, optional = false)
private Credit credit;
}
In select statements, the two approaches are accepted, but I don't understand why Hibernate have this limitation or if I'm doing something wrong in my DELETE Jpql. I would like to declare the JOIN in the query.
The only way that I know to resolve this problem in more complex queries is create a subselect:
delete from Order order WHERE order.id IN (
SELECT order.id FROM Order order
JOIN order.credit credit
WHERE credit.id in ?1)
Is this the right approach for more complex delete queries?
I'm using the Spring Jpa Repository in the code above and Spring Boot 1.5.10.RELEASE.
I don't understand why Hibernate have this limitation.
It is specified as such in the JPA Spec in section 4.10:
delete_statement ::= delete_clause [where_clause]
delete_clause ::= DELETE FROM entity_name [[AS] identification_variable]
So joins aren't allowed in delete statements.
Why this was decided this way is pure speculation on my side.
But the select_clause or delete_clause specify what the query operates on. While it is totally fine for a select statement to operate on a combination of multiple entities a join for a delete doesn't really make much sense.
It just forces you to specify which entity to delete.
The only way that I know to resolve this problem in more complex queries is to create a subselect:
Is this the right approach for more complex delete queries?
If you can't express it using simpler means then yes, this is the way to go.

Reduce number of queries for JPQL POJO containing an entity

Entity relation: Transaction(#ManyToOne - eager by default) -> Account
String sql = "SELECT new com.test.Pojo(t.account, SUM(t.value)) FROM Transaction t GROUP BY t.account";
List list = entityManager.createQuery(sql).getResultList();
By default JPA using Hibernate implementation will generate 1 + n queries. The n queries are for lazy loading of the account entities.
How can I make this query eager and load everything with a single query? The sql equivalent would be something like
SELECT account.*, SUM(t.value) FROM transactions JOIN accounts on transactions.account_id = accounts.id GROUP BY account.id
, a syntax that works well on PostgreSQL. From my findings Hibernate is generating a query that justifies the lazy loading.
SELECT account.id, SUM(t.value) FROM transactions JOIN accounts on transactions.account_id = accounts.id GROUP BY account.id
Try marking the #ManyToOne field as lazy:
#ManyToOne(fetch = FetchType.LAZY)
private Account account;
And change your query using a JOIN FETCH of the account field to generate only one query with all you need, like this:
String sql = "SELECT new com.test.Pojo(acc, SUM(t.value)) "
+ "FROM Transaction t JOIN FETCH t.account acc GROUP BY acc";
UPDATE:
Sorry, you're right, the fetch attribute of #ManyToOne is not required because in Hibernate that is the default value. The JOIN FETCH isn't working, it's causing a QueryException: "Query specified join fetching, but the owner of the fetched association was not present".
I have tried with some other approaches, the most simple one that avoids doing n + 1 queries is to remove the creation of the Pojo object from your query and process the result list, manually creating the objects:
String hql = "SELECT acc, SUM(t.value)"
+ " FROM " + Transaction.class.getName() + " t"
+ " JOIN t.account acc"
+ " GROUP BY acc";
Query query = getEntityManager().createQuery(hql);
List<Pojo> pojoList = new ArrayList<>();
List<Object[]> list = query.getResultList();
for (Object[] result : list)
pojoList.add(new Pojo((Account)result[0], (BigDecimal)result[1]));
Well PostgreSQL (And any other SQL database too) will block you from using mentioned query: you have to group by all columns of account table, not by id. That is why Hibernate generates the query, grouping by ID of the account - That is what is intended to be, and then fetching the other parts. Because it cannot predict in general way, what else will be needed to be joined and grouped(!!!), and in general this could produce situation, when multiple entities with the same ID are fetched (just create a proper query and take a look at execution plan, this will be especially significant when you have OneToMany fields in your Account entity, or any other ManyToOne part of the Account entity) that is why Hibernate behaves this way.
Also, having accounts with mentioned IDs in First level cache, will force Hibernate to pick them up from that. Or IF they are rarely modified entities, you can put them in Second level cache, and hibernate will not make query to database, but rather pick them from Second level cache.
If you need to get those from database in single hint, but not use all the goodness of Hibernate, just go to pure JPA Approach based on Native queries, like this:
#NamedNativeQuery(
name = "Pojo.groupedInfo",
query = "SELECT account.*, SUM(t.value) as sum FROM transactions JOIN accounts on transactions.account_id = accounts.id GROUP BY account.id, account.etc ...",
resultClass = Pojo.class,
resultSetMapping = "Pojo.groupedInfo")
#SqlResultSetMapping(
name = "Pojo.groupedInfo",
classes = {
#ConstructorResult(
targetClass = Pojo.class,
columns = {
#ColumnResult(name = "sum", type = BigDecimal.class),
/*
* Mappings for Account part of entity.
*/
}
)
}
)
public class Pojo implements Serializable {
private BigDecimal sum;
/* .... */
public Pojo(BigDecimal sum, ...) {}
/* .... */
}
For sure this will work for you well, unless you will use the Account, fetched by this query in other entities. This will make Hibernate "mad" - the "entity", but not fetched by Hibernate...
Interesting, the described behaviour is as if t instances are returned from the actual query and t.account association in the first argument of Pojo constructor is actually navigated on t instances when marshalling results of the query (when creating Pojo instances from the result rows of the query). I am not sure if this is a bug or intended feature for constructor expressions.
But the following form of the query should work (no t.account navigation in the constructor expression, and no join fetch without the owner of the fetched association because it does not make sense to eagerly initialize something that is not actually returned from the query):
SELECT new com.test.Pojo(acc, SUM(t.value))
FROM Transaction t JOIN t.account acc
GROUP BY acc
EDIT
Very good observation by Ilya Dyoshin about the group by clause; I completely oversaw it here. To stay in the HQL world, you could simply preload all accounts with transactions before executing the query with grouping:
SELECT acc FROM Account acc
WHERE acc.id in (SELECT t.account.id FROM Transaction t)

JPQL Query Bulk UPDATE SET on an ElementCollection field

I have the following JPA Entity I want to update:
#Entity(name = "EmployeeImpl")
#Table(name = "EmployeeImpl")
public class EmployeeImpl {
#Id
#Column(name = "employeeId")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#ElementCollection
private List<String> phonenumber;
}
I thought I use a namedQuery like so
#NamedQuery(name = "updateEmployee",
query = "Update EmployeeImpl e SET e.phonenumber :number WHERE e.id = :id")
But that doesn't work: Exception Description: Error compiling the query [updateEmployee: Update EmployeeImpl e SET e.phonenumber = :number WHERE e.id = :id], line 1, column 28: invalid access of attribute [phonenumber] in SET clause target [e], only state fields and single valued association fields may be updated in a SET clause.
Question is, how do I update an #ElementCollection? If it's possible i'd like to do it with a jpql query.
No, that is not possible in JPQL. As kostja says: the message says it clear and also according to the JPA specification, Chapter "4.10 Bulk Update and Delete Operations" you may update only state fields and single values object fields.
The syntax of these operations is as follows:
update_statement ::= update_clause [where_clause]
update_clause ::= UPDATE entity_name [[AS] identification_variable]
SET update_item {, update_item}*
update_item ::= [identification_variable.]{state_field | single_valued_object_field} = new_value
new_value ::=
scalar_expression |
simple_entity_expression |
NULL
WHAT TO DO?
Probably the most clean way to do that is simply to fetch the entities and to add/replace the phone number/s, although you can always do that also with Native Queries, i.e SQL queries as kostja says.
The reason for the failure is stated in the error message. You cannot use bulk updates on non-singular attributes of your entity, since they are stored in a different table.
How do you do it instead? You update the collection table.
The default table name for collection tables is <parent_entity>_<field_name>. So the table you are interested in should be named EmployeeImpl_phonenumber. The id column for the EmployeeImpl (the foreign key) should be named EmployeeImpl_id per default.
EDIT What I posted initially was not valid in JPQL. You might want to use a native query instead. It is simple, so it should be portable:
The native query could then look like this:
UPDATE EmplyeeImpl_phonenumber
SET phonenumber = ?
WHERE employeeimpl_id = ?

named native query and mapping columns to field of entity that doesn't exist in table

I have a named native query and I am trying to map it to the return results of the named native query. There is a field that I want to add to my entity that doesn't exist in the table, but it will exist in the return result of the query. I guess this would be the same with a stored proc...
How do you map the return results of a stored proc in JPA?...
How do you even call a stored proc?
here is an example query of what I would like to do...
select d.list_id as LIST_ID, 0 as Parent_ID, d.description from EPCD13.distribution_list d
The Result will be mapped to this entity...
public class DistributionList implements Serializable {
#Id
#Column(name="LIST_ID")
private long listId;
private String description;
private String owner;
private String flag;
#Column(name="PARENT_ID", nullable = true)
private long parentID;
}
parent ID is not in any table in my database. I will also need to use this entity again for other calls, that have nothing to do with this call, and that will not need this parent_id? Is there anything in the JPA standard that will help me out?
If results from database are not required for further manipulation, just for preview, you can consider using database view or result classes constructor expression.
If entities retrieved from database are required for further manipulation, you can make use of multiple select expression and transient fields.
Replace #Column annotation with #Transient annotation over parentID.
After retrieving multiple columns from database, iterate over results and manually set parentID.

JPA criteriabuilder "IN" predicate on foreign key error: Object comparisons can only use the equal() or notEqual() operators

I want to select a list of file references from a table by looking at which users have the rights to retrieve that file. To do this I have 3 tables, a file table, an access control table, and a users table.
I am using JPA and Criteriabuilder (because there are more tables involved and I need dynamicle create the query, I am leaving out the other tables and predicates from this question for the sake of readability).
The following code works
CriteriaBuilder queryBuilder = em.getCriteriaBuilder();
CriteriaQuery<File> queryDefinition = queryBuilder.createQuery(File.class);
Root<File> FileRoot = queryDefinition.from(File.class);
List<Predicate> predicateList = new ArrayList<Predicate>();
Predicate userPredicate = FileRoot .join("FileAccesControlCollection").join("userId").get("usersId").in(loggedInUser.getUsersId());
predicateList.add(userPredicate );
queryDefinition.where(predicateArray).distinct(true);
Query q = em.createQuery(queryDefinition);
List<Files> results = (List<Files>) q.getResultList();
For the userpredicate I want to leave out the last join to the users table because the ID that I want to filter on is already present in the FileAccesControlCollection table, and a join is a computational expensive database operation.
What I tried is to do this:
Predicate userPredicate = FileRoot .join("FileAccesControlCollection").get("usersId").in(loggedInUser.getUsersId());
But I guess because the userId value in the FileAccesControlCollection entity class is a foreignkey reference to the Users class I get the following error:
Exception Description: Object comparisons can only use the equal() or notEqual() operators. Other comparisons must be done through query keys or direct attribute level comparisons.
Is there a way, using the loggedInUser entity or its Id, to filter the files by just joining the File class to the FileAccesControlCollection class and filtering on the userId foreign key? I am kind of new to JPA and using google lead me to a lot of pages but not a clear answer for something which seems to me should be possible.
So "userId" is mapped as a OneToOne? Then you could do,
get("userId").get("id").in(...)
You could also add a QueryKey in EclipseLink using a DescriptorCustomizer for the foreign key field and then use it in the query,
get("userFk").in(...)
try this:
Predicate userPredicate = FileRoot.join(FileAccesControlCollection.class).join(Users.class).get("{id field name in class Users}").in(loggedInUser.getUsersId());
good luck.