JPA: Querying an object and single values from other entity - jpa

Is it possible with JPA to query a database to get an entity filled with an additional field belonging to another table/entity?
I have a reservations table holding a foreign key to a record(an entity) in another table pois which has to columns of interest: poiId and poiType.
Instead of having a field ReservationEntity.poi (to finally obtain poi.poiType) I want to have a ReservationEntity.poiId and ReservationEntity.poiType and I wonder if it's possible to achieve this through a NamedQuery:
#NamedQuery(name="ReservationEntity.findByRfId", query="SELECT r, p.poiType FROM ReservationEntity r LEFT JOIN PoiEntity p ON r.poiId = p.poiId WHERE r.rfId = :rfId")
...since you read my question you can imagine that this DOESN'T work. ;-)
Is it possible to do it in such a kind?
Here's the exception:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'POITYPE' in 'field list'
Error Code: 1054
Call: SELECT reservationId, endTime, notification, poiId, POITYPE, startTime, status, timeZone, tstamp, type FROM reservations WHERE (reservationId = ?)
bind => [1 parameter bound]
Query: ReadObjectQuery(name="ReservationEntity.findById" referenceClass=ReservationEntity sql="SELECT t1.reservationId, t1.authInfo, t1.endTime, t1.evsp, t1.notification, t1.poiId, t1.POITYPE, t1.startTime, t1.status, t1.timeZone, t1.tstamp, t1.type FROM reservations t1 LEFT OUTER JOIN pois t0 ON (t1.poiId = t0.poiId) WHERE (t1.reservationId = ?)")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)

By now I made it work using a database view instead of a table for the #Entity(...) annotation.
Yet I don't have the requirement to update the entity. However, it is possible to update a view as long as only one table' column are modified and an INNER JOIN is used: http://dev.mysql.com/doc/refman/5.6/en/view-updatability.html

Related

how to call spring jap query none parameters

I use spring data jpa with native query
I have already some query like this
How to use native query none parameter.
String q="SELECT t1.blockNumber-1 FROM someTAble t1 LEFT JOIN someTAble t2 ON t2.blockNumber = t1.blockNumber-1 WHERE t2.blockNumber IS NULL AND t1.blockNumber> 0 ORDER BY t1.blockNumber";
#Query(value = q,nativeQuery = true)
List<Entity> findByBlockNumberIs();
they are occur errors Column 'sequence' not found.
That query means are when i insert some Contiguous data int value then i find missing data.
But
this query working
SELECT *,t1.blockNumber-1 FROM someTAble t1 LEFT JOIN someTAble t2 ON t2.blockNumber = t1.blockNumber-1 WHERE t2.blockNumber IS NULL AND t1.blockNumber> 0 ORDER BY t1.blockNumber
The difference between the two queries is whether there is a '*' or not
how to change simple to my query.
How to i changed error
OR How to use spring data jpa predicate
QEntity qBe1= QEntity .blockEntity;
QEntity qBe2= QEntity .blockEntity;
build.and(qBe2.blockNumber.eq(be.getBlockNumber()-1))
.and(qBe2.blockNumber.isNull().and(qBe1.blockNumber.gt(0)));
is predicate can use left join?
well...
use this.
List<Integer> findByBlockNumber()

construct select to return an entity using criteria builder

Using JPQL I could write something similar to this:
select p.name, p.surname, e from Person p, Employee e
in this way a cartesian product is done and the full employee entity will be returned.
Using a left join:
SELECT p.name, p.surname, e FROM Person p LEFT JOIN p.employees e
I would like to create the second query using criteria builder api.
How could I do that ?
Update:
Using criteria I could do something like this:
Join join = root.join("employees", JoinType.LEFT);
CompoundSelection select = cb.array(
root.get("name"),
root.get("surname"),
join)
But using this query I got the error:
javax.persistence.PersistenceException: Exception [EclipseLink-6044] (Eclipse
Persistence Services - 2.5.1.v20130918-f2b9fc5):
org.eclipse.persistence.exceptions.QueryException Exception Description: The primary key
read from the row [DatabaseRecord(EMPLOYEE.NUMBER => null
EMPLOYEE.ADDRESS => null)] during the execution of the query was detected to be
null.
Primary keys must not contain null.
Because eclipse link is unable to "construct" the employee object because it doesn't exist (it is a left join, so in my scenario it is possible that it doesn't exist).

Entity Framework 5: How to Outer Join Table Valued Function

I'm attempting to outer join a table with an inline table valued function in my LINQ query, but I get a query compilation error at runtime:
"The query attempted to call 'OuterApply' over a nested query, but 'OuterApply' did not have the appropriate keys."
My linq statement looks like this:
var testQuery = (from accountBase in ViewContext.AccountBases
join advisorConcatRaw in ViewContext.UFN_AccountAdvisorsConcatenated_Get()
on accountBase.AccountId equals advisorConcatRaw.AccountId into advisorConcatOuter
from advisorConcat in advisorConcatOuter.DefaultIfEmpty()
select new
{
accountBase.AccountId,
advisorConcat.Advisors
}).ToList();
The function definition is as follows:
CREATE FUNCTION dbo.UFN_AccountAdvisorsConcatenated_Get()
RETURNS TABLE
AS
RETURN
SELECT AP.AccountId,
LEFT(AP.Advisors, LEN(AP.Advisors) - 1) AS Advisors
FROM ( SELECT DISTINCT
AP.AccountId,
( SELECT AP2.PropertyValue + ', '
FROM dbo.AccountProperty AP2 WITH (NOLOCK)
WHERE AP2.AccountId = AP.AccountId
AND AP2.AccountPropertyTypeId = 1 -- Advisor
FOR XML PATH('')) AS Advisors
FROM dbo.AccountProperty AP WITH (NOLOCK)) AP;
I can successfully perform the join directly in sql as follows:
SELECT ab.accountid,
advisorConcat.Advisors
FROM accountbase ab
LEFT OUTER JOIN dbo.Ufn_accountadvisorsconcatenated_get() advisorConcat
ON ab.accountid = advisorConcat.accountid
Does anyone have a working example of left outer joining an inline TVF to a table in LINQ to entities - or is this a known defect, etc? Many thanks.
Entity Framework needs to know what the primary key columns of the TVF results are to do a left join. Basically you need to create a fake table which has same schema as your TVF results and update TVF in model browser to return the new created table type instead of default complex type. You could refer to this answer to get more details.

How do I traverse a relationship in a WHERE clause with OpenJPA?

I am new to JPA and OpennJPA. I have two entities UserDmo and SupplierDmo. Each Supplier can have several users and this relationship is established as follws,
In UserDmo,
Column(name="id_supplier")
private long idSupplier;
#ManyToOne(optional=true)
#JoinColumn(name="ID_SUPPLIER")
private SupplierDmo supplier;
In here column ID_SUPPLIER is the FK with referenced by ID column of the SupplierDmo. Using these two entities I tried to obtain result by following query.
SELECT u.id, u.modifiedDate FROM UserDmo u JOIN u.idSupplier s WHERE s.id = 1
But I got, Error message: Attempt to query field "s.id" from non-entity variable "s". Perhaps you forgot to prefix the path in question with an identification variable from your FROM clause?
I really appreciate your help on this
Try something like this :
SELECT u.id, u.modifiedDate FROM UserDmo u WHERE u.supplier.id = 1

Why does JPQL's "OR" operator narrow result set?

I have three tables: "User", "Employee" and "Worker". "User" table has one-to-zero-or-one relationship with "Worker" and the same one-to-zero-or-one with "Employee". User entity bean has following mapping attributes:
#OneToOne(cascade = CascadeType.ALL, mappedBy = "user")
private Worker worker;
#JoinColumn(name = "id_employee", referencedColumnName = "id")
#OneToOne
private Employee idEmployee;
My aim is to get all "User" records which have one of this attributes filled (not null). I try to use the query:
SELECT u FROM User u WHERE u.idEmployee IS NOT NULL OR u.worker IS NOT NULL
ORDER BY u.login
I suppose to get 15 records, but I get only 6. I divided this query into two separate:
SELECT u FROM User u WHERE u.idEmployee IS NOT NULL ORDER BY u.login;
SELECT u FROM User u WHERE u.worker IS NOT NULL ORDER BY u.login;
I get 9 and 6 records, respectively. Put together - required 15 records.
It looks like "OR" narrows the result set to only those records, which have worker field not null. Why does it work in such way? Thanks in advance.
The worker association is mapped by a foreign key in the worker table. This means that using u.worker makes an inner join to the worker table, and the is not null is always true. The resulting SQL should look like this:
select u.* from user u, worker w where u.id = w.user_id and w.user_id is not null.
You need to use a left join to accept users having no worker:
select u from User u
left join u.worker w
left join u.employee e
where w is not null or e is not null
i actually had similar problem recently, and it turns out i was using old version of eclipse link, where statements is null and is not null wasn't correctly executed if they were part of and/or statement.
If i remember fix for that was in eclipse link 2.2.0. if you are not using eclipse link, ignore my post.