Specification in Spring JPA, 'not in' Query - spring

can't make work not in query.
There are tables User and Relation. Relation contains 2 fields with reference on User: user and other. I need records from User that are not referenced as Relation.other.
Trying compose this way:
return (root, query, builder) -> {
Subquery<Relation> subQuery = query.subquery(Relation.class);
Root<Relation> subQueryRoot = subQuery.from(Relation.class);
subQuery.select(subQueryRoot);
Predicate userPredicate = builder.equal(subQueryRoot.get("user"), user);
return builder.not(
builder.in(
subQuery.select(subQueryRoot.get("other")).where(userPredicate)
)
);
};
but the result is such SQL:
-- othere conditions
and (
(
select
relation1_.other_id
from
relation relation1_ cross
join
user user2_
where
relation1_.other_id=user2_.id
and relation1_.user_id=?
) not in (
null
)
)
How to fix it?

Related

sql query into raw query in laravel

I am new in laravel . I have laravel 5.7 version. and I have query
like
$emp_id = $request->user_id;
$User_workDone_record = DB::select(
DB::raw("
SELECT
(
SELECT access(id) FROM users where id = $emp_id
) as accessid,
a.date as date,
a.day as day,
a.projectname as projectname,
a.clientname as clientname,
task,
start,
(
SELECT users(id) FROM `users` where id = $emp_id
) as user,
end,
TIMEDIFF(end,start) as diff,
workdetails,
id,
rowpages
FROM
workdone as a
where
a.user = '$emp_id'
order by
a.date desc
")
);
but I got issue like :
SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION workdoneerp.access does not exist (SQL: SELECT(SELECT access(id) FROM users where id=9) as accessid, a.date as date,a.day as day,a.projectname as projectname,a.clientname as clientname,task,start,end,TIMEDIFF(end,start) as diff,workdetails,id,rowpages FROM workdone as a where a.user='9' order by a.date desc),
How to resolve ?
The problem is access(id) at the start of your SQL query.
The error is telling you the access() function does not exist in your database (workdoneerp).
To solve it you can
create the access() function
or don't use the access() function.

GroupBy query with Querydsl and Spring Boot

I have two entities, one is Client and the other is Transactions and they are linked #OneToMany respectively.
I would like to create a query using Querydsl that will filter my clients based on the count of their transactions. Basically I want this SQL query
SELECT * FROM client WHERE id IN (SELECT client_id
FROM (SELECT client_id, count(client_id) as 'count' from transaction group by client_id) as t
where t.count >= 10)
to be done in Querydsl. The problem is I want to return a BooleanExpression so I can aggregate the query further, i.e AND it or OR it with some other query.
The Querydsl entities are QClient and QTransaction respectively.
This is my current code,
QClient client = QClient.client1;
QTransaction transaction = QTransaction.transaction;
var count = Expressions.numberPath(Long.class, "count");
var subquery = JPAExpressions.select(transaction.client.id, transaction.client.id.count().as(count))
.from(transaction).groupBy(transaction.client.id).where(count.gt(depositCount)).select(transaction.client.id);
return client.id.in(subquery);
It doesn't work in this form.
How about this?
Note this is in context to my test project at https://github.com/gtiwari333/spring-boot-web-application-seed. But you can easily apply the same for your tables.
Ref: https://github.com/gtiwari333/spring-boot-web-application-seed/blob/master/main-app/src/main/java/gt/app/modules/article/ArticleRepositoryCustomImpl.java#L48
public void doQuery() {
QArticle qArticle = QArticle.article;
QUser user = QUser.user;
var subquery1 = JPAExpressions
.select(qArticle.createdByUser.id)
.from(qArticle)
.groupBy(qArticle.createdByUser.id)
.having(qArticle.id.count().gt(5));
BooleanExpression exp = user.id.in(subquery1);
BooleanExpression exp2 = qArticle.title.length().lt(15);
List<Article> ar = from(qArticle)
.join(user).on(qArticle.createdByUser.id.eq(user.id))
.select(qArticle)
.where(exp.and(exp2))
.fetch();
System.out.println(ar);
}
Also, your query can be simplified.
SELECT * FROM client WHERE id IN
( SELECT client_id FROM
(SELECT client_id, count(client_id) as 'count' from ransaction group by client_id)
as t where t.count >= 10)
to:
SELECT * FROM client
WHERE id IN ( SELECT client_id
FROM
TRANSACTION
GROUP BY
client_id
HAVING
count(client_id)> 10)

Select from junction table

everybody!
What should I do if I need to make select from junction table?
For example, I develop project and I need to make chats between users. I have two entities: User and Chat, and many-to-many relation between them (accordingly, I have three tables: user, chat, chat_user). I try to get all chats, which user is member, and to get all users from these chats.
I made the following SQL query:
SELECT *
FROM chat c
INNER JOIN chat_user cu ON c.id = cu.chat_id
INNER JOIN user u ON u.id = cu.user_id
WHERE c.id IN (SELECT chat_id
FROM chat_user
WHERE user_id = <idUser>);
But I don't know how to translate in DQL subquery SELECT chat_id FROM chat_user WHERE user_id = <idUser>, because a haven't additional entity for table chat_user.
And I tried to add entity ChatUser and get data in ChatRepository smt. like this:
public function getChatsData($idUser)
{
$subQuery = $this->getEntityManager()
->getRepository(ChatUser::class)
->createQueryBuilder('chus')
->select('chus.chat')
->andWhere('chus.user = :idUser')
->setParameter('idUser', $idUser)
;
$qb = $this->createQueryBuilder('c');
return $qb
->innerJoin('c.chatUsers', 'cu')
->addSelect('cu')
->innerJoin('cu.user', 'u')
->addSelect('u')
->innerJoin('c.messages', 'm')
->addSelect('m')
->andWhere('u.id = :idUser')
->andWhere($qb->expr()->in(
'c.id',
$subQuery->getDQL()
))
->setParameter('idUser', $idUser)
->getQuery()
->getResult()
;
}
but it doesn't work. I get error [Semantical Error] line 0, col 12 near 'chat FROM App\Entity\ChatUser': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
Have Doctrine standard tools for such tasks?

Use SUMMARIZECOLUMNS on table union in DAX query

I am trying to write a DAX query that runs the SUMMARIZECOLUMNS function on a table variable. The table variable is the union of two tables that have the same columns in the same order.
When I try to run the query, I get a Cannot find table error. Here is the query I am trying to run:
EVALUATE
VAR u = UNION(Table1, Table2)
RETURN SUMMARIZECOLUMNS(u[CreationYear], u)
How can I run this query on the union of the two tables?
It's not very elegant, but in response to your comment on Marco's solution, you can do a count like this:
EVALUATE
VAR u = UNION(Table1, Table1)
RETURN SUMMARIZE(u, [CreationYear],
"Count",
COUNTX(
FILTER(u,
[CreationYear] = EARLIER([CreationYear])
),
[Id]
)
)
Try using SUMMARIZE in stead of SUMMARIZECOLUMNS. Like this:
EVALUATE
VAR u = UNION ( Table1, Table2 ) RETURN SUMMARIZE ( u, [CreationYear] )

System.Linq.Dynamic to select a collection inside of a collection from Entity Framework IQueryable

I have an EF model with the relationship User->Roles. It's a one to many relationship in our database. I would like to select the ID from role's record and the name from the user's records.
What I have come up with works for one-to-one relationships. I'm not sure how to generate the a list inside of dynamic linq. Maybe a SelectMany?
User table: Users
Join Table: User_Role
Role Table: Roles
//does not select inside a collection of USER_ROLES
q= query.Select(" new ( ID, (new (USER_ROLES.ID as ID) as USER)")
//not valid
//q = query.Select(" new ( ID, (new List<Object> (USER_ROLES.ID as ID) as USER)") something I figure this would give me a list of User_Role's ID
//not valid
//q = query.Select(" new ( ID, (new List<Object> (USER_ROLES.ROLE.ID as ID) as USER)") something I figure this would give me a list of Role's ID
Update I'm getting closer. I used a selectmany, but the results are duplicated
q = query.SelectMany("USER_ROLES","new (inner as myUSER,outer as myROLE) ").SelectD("new (myROLE.ID as ROLE_ID, new( myROLE.NAME, myUSER.USER.FIRSTNAME,myUSER.USER.ID)as user)")
The results look like this:
Role->User_Role A-> User A
User_Role A-> User B ..notice the repeat of "User_Role A"
User_Role A-> User C
it should be
Role->User Role a -> User A
+ User B
+ User C

Resources