Problem with MongoDB #Query annotation/Query - spring-boot

I got problems with #Query annotation or Query query = new Query() - I can't include/exclude some fields.
I find code samples like:
#Query(value = "{'id': ?0}",fields = "{'id':1}")
User findUserById(String id);
Result should be user with only one field -> id but its showing other fields to..
So I found other samples like:
Query query = new Query();
query.fields().include("id");
query.addCriteria(Criteria.where("id").is(id));
User one = mongoTemplate.findOne(query, User.class);
Same result there..
Any ideas?

Integer findUserById(String id);
Use the DataType of Id [like Integer] to get only id.
Change datatype of according the requirement/usecase

Related

How can I write a custom query with spring in mongo?

I'm trying to make a query and fetch data over mongodb with Spring. But I don't know mongo and spring very well. I have these fields in my table. How can I write a custom query with this query in SQL? I mean give the qp value of the record whose id is this. How can I write this please help..
SELECT qp
FROM tableName
WHERE id = request.getId();
my custom query method is it true?
public Object findQueryParams(ProcessInfo processInfo ){
Query query = Query.query(Criteria.where("id").is(processInfo .getId()).is(processInfo .getQueryParams()));
return query;
}

EntityManager createQuery with single column throws type error

I am using LocalContainerEntityManagerFactoryBean and OracleUCPConfig
I have class EmployeeEntity.java mapped to table employee
I have written a createQuery code as
Query query = em.createQuery("select id from Employee", EmployeeEntity.class);
query.getResultList()
I am getting error as:
Type specified for TypedQuery [EmployeeEntity] is incompatible with [java.lang.String]
how do I solve this issue?
I want all ids from the table not any other fields needs to retrieved
--EDIT--
I solved the issue by change the JQL to JPQL
Query query = em.createQuery("select new EmployeeEntity(id) from Employee", EmployeeEntity.class);
query.getResultList()
you are mapping id to type EmployeeEntity, if you check your query, you are extracting only id instead of everything: select id from Employee. you can fix this by changing your query to:
Query query = em.createQuery("select e from Employee e", EmployeeEntity.class);
if you need only id column you could do something like:
TypedQuery<String> query = em.createQuery("select e.id from Employee e", String.class);
List<String> ids = query.getResultList();
The second parameter of createQuery() is the type of the query result. In your case, the result type is String (a list of Strings), as you only SELECT the column id.
So this should work:
Query query = em.createQuery("select e.id from Employee e", String.class);
List<String> ids = query.getResultList();

What is entity reference and Query Expression ? Please give some simple examples

What is EntityReference and QueryExpression? Please give me some simple examples.
EntityReference
It is used for lookup fields in
365 – e.g. to link records via a 1 to many relationship. The lookup
field is shown on the ‘child’. You need to specify the ‘parent’ entity
type and record id.
For example if you are creating a accountand want to set the primary contact.
Entity account = new Entity("account");
account["name"] = "James Account";
account["primarycontactid"] = new EntityReference("contact", contactId);
service.Create(account);
QueryExpression
QueryExpression provides an object model to construct a query. Queries
can also be created using FetchXML, a proprietary XML based query
language.
For example of you wanted to retrieve all contacts full name and telephone number.
QueryExpression query = new QueryExpression()
{
Distinct = false,
EntityName = Contact.EntityLogicalName,
ColumnSet = new ColumnSet("fullname", "address1_telephone1"),
};
DataCollection<Entity> entityCollection = _service.RetrieveMultiple(query).Entities;

How to Return all instances of the type with the given ID in JPA SpringBoot?

I'm trying to return (or fetch) all the records from the database based on an ID provided by me. I'm using JPA and i'm aware of findAll() method but it returns all the records without any criteria, I created a custom query and it is only returning a unique value from the table but i want to return all records based on a criteria.
For example, findAllByUserID(String UserID) method should return all the records based on that UserID not just one.
I'd appreciate any help or suggestion.
Thanks
Have a look at the doc. There you will find the keywords you can use to declare methods in repository interfaces that will generate the according queries:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
In your case: If userID is an attribute of your entity you can add a method
List<YourEntity> findByfindAllByUserID(String userId)
to your repository interface.
First, make sure that you're not using any aggregate function in your select query such as DISTINCT()
Then make sure that the the method which is implementing that query is returning a List of you're desired result.
here's how it should look :
#Query("select t from table t where t.code = ?1")
List<Result> findAllByUserID(String UserID);

Spring-Data JPA: How to make a jpa criteria query

Given this two entities:
post post_category
- id - post_id
- title - name
- text
I'd like to make this query using jpa criteria query:
select * from post
where post.id in (
select post_id from post_category
where name = '<category1>' and name = '<category2>' ... and name = '<categoryN>')
Looking at your query sketch I think it will not return any results. I have changed it to mean name in ('<category1>','<category2>', ...) instead. Which may not match your case.
This assumes that you have your mapping set up properly on your classes for JPA to work. For example
class PostCategory {
private String name;
private Post post;
...
#ManyToOne
public Post getPost() {
return post;
}
...
In which case your DAO code would resemble this (given a List nameValues object)
// Set up the subquery
DetachedCriteria dc = DetachedCriteria.forClass(PostCategory.class)
.setProjection(Projections.property("post.id"))
.add(Restrictions.in("name", nameValues));
Criteria crit = session.createCriteria(Post.class)
.add(Subqueries.eqProperty("id", dc));
But if you want a list of Post objects which have ALL of the categories then you will need to make a separate DetachedCriteria instance for each category and add each as an AND'ed Subquery.

Resources