Error while using Jparepository - java

I was using JPA repository to get user data and store it in a list . Then is was going to iterate that list of users to get all the users. But there is an error in the forEach statement(Syntax error).
code:
package com.mohit.Services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.mohit.Repo.userrepo;
import com.mohit.beans.users;
public class loginuser {
#Autowired
userrepo Repo;
public void loguser(users user){
String pass =user.getPass();
String uname =user.getName();
List<users> userlist=Repo.findAll();
forEach( users u : userlist){
}
}
}

There is no foreach keyword in java, need to use for, so you have error in source code, please try below code for cycle, instead of your's:
for(users u : userlist){
}

Related

Spring — Passing List<String> of values in Payload POST API to Springframework.data.jpa.repository.Query "IN"

Lets assume we have one table/View with below columns
columns : ID , Status
I am writing one search API to get Data from backend
I am using org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
.....
#Repository
#Transactional
public interface UIDashboard extends JpaRepository<UIDashboardView, String> {
....
#Query(value = "SELECT results from SearchView results where "
+ "(:status is null or results.STATUS = :status) and"
+ "(coalesce(:ids) is null or results.ID in :ids)"
...
My DTO
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.util.Optional;
import lombok.Data;
#Data
#JsonInclude(Include.NON_NULL)
public class SearchInputDTO {
#JsonProperty(value="status",required = false)
private String status;
#JsonProperty(value="ids",required = false)
//private Optional<List<String>> ids;
//ArrayList<String> ids;
private List<String> ids;
REST API
import org.springframework.web.bind.annotation.PostMapping;
...
#PostMapping("/searchTest")
public ResponseEntity<List<ResultsDTO>> search_test(
#RequestBody #NotNull #Valid SearchInputDTO payload, HttpServletRequest request)
throws IOException {
}
{
"status" : "COMPLETED",
"ids" : [null,null]
}
Issue with the approach is to invoke POST REST API i need to send two null values [null,null] in payload i,e without id's property i am unable to execute POST API , so either i need to send null values or set in DTO.
I also tried to make Optional in DTO or
Used coalesce -> (coalesce(:ids) is null or results.ID in :ids)
i dont want to explicitly send null values in Payload , User can search with any parameter for example only with one property :status:
{
"status" : "INPROCESS"
}
Above payload not working as i am not sending "ids"
Then i tried set nulls in setter as workaround
#JsonProperty(value="ids",required = false)
private List<String> ids = new ArrayList<>(Arrays.asList(null, null));
#JsonSetter("ids")
public void setIds(List<String> li){
if (li != null) {
if (li.size() < 2){
li.add(null);
li.add(null);
this.ids = li;
}
else{
this.ids = li;
}
}
}
I dont like this work around , is there any better solution or changes required to JPQL IN parameter or SearchInputDTO .
I also followed blog Spring Data repository with empty IN clause
Thanks,
Showkath.

Multiple queries in the same view

I would like to run multiple queries then show results in a page such as :
https://adminlte.io/themes/v3/index.html
I create a first controller query :
package controllers;
import models.Sysuser;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import views.html.sitemap.index;
import javax.inject.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import play.libs.concurrent.HttpExecutionContext;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import play.db.*;
import io.ebean.*;
import play.Logger;
import java.util.List;
import java.util.ArrayList;
import models.LocationExtractedData;
#Security.Authenticated(Secured.class)
public class SiteMap extends Controller {
private Database db;
private final HttpExecutionContext httpExecutionContext;
private static final Logger.ALogger logger = Logger.of(SiteMap.class);
#Inject
public SiteMap(Database db,
HttpExecutionContext httpExecutionContext) {
this.db = db;
this.httpExecutionContext = httpExecutionContext;
}
public CompletionStage<Result> index() {
return SearchSomething().thenApplyAsync((List<LocationExtractedData> infos) -> {
return ok(views.html.sitemap.index.render( Sysuser.findByUserName(request().username()), infos) );
}, httpExecutionContext.current());
}
public CompletionStage<List<LocationExtractedData>> SearchSomething() {
return CompletableFuture.supplyAsync(() -> {
return db.withConnection(
connection -> {
// Imagines this is a complexe QUERY (Later in the future...)
final String sql = "SELECT sysuser_id, role_id "
+"from sysuser_role "
+"where sysuser_id = '1' "
+"and role_id in ('1','2','3','4','5') ";
final RawSql rawSql = RawSqlBuilder.parse(sql).create();
Query<LocationExtractedData> query = Ebean.find(LocationExtractedData.class);
query.setRawSql(rawSql);
List<LocationExtractedData> list = query.findList();
return list;
});
}, httpExecutionContext.current());
}
}
Can you telling me how to run multiple and optimized queries in the same time for my page full of dashboards, charts and tables!
If i create multiple list of ebeanLists ( queries ), does this will affect the loading of my page ?
IF not, then, what should i do ?
Thank you in advance,
Typically, in an application similar to the link you have provided, you create reusable APIs following the MVC design pattern. Querying the database from the controller is very much against that pattern.
Each API should be atomic, creating a single API to run 1 query to fetch all of the data for that page is not the correct approach.
If you are looking for performance for your API you should get familiar with asynchronous programming. Running your APIs async will allow your back end to process multiple front end requests at the same time, greatly improving performance.

MongoShell query to MongoRepository

db.getCollection('parentCollection').find({"mapObject.someField" : {$exists: true}})
i want this to convert into method like below
.
#Query("{mapObject.someField :{$exists : true}}")
List<Parent> findByMapKey(String id);
Here i am getting null pointer exception while running application
#Query("{mapObject.someField :{$exists : true}}")
here someField needs to be dynamic not fixed so i want my id to be passed in place of someField
Same question exists here as well
How to get parent object based upon key from child map in MongoRepository JAVA SpringBoot
It's not possible to do with MongoRepository. Instead, use MongoTemplate.
As mentioned above by #Valijon it is not possible with #Query annotation. Still if anyone finds a way please share. Following is how i achieved it using MongoTemplate
package com.somepackage.services;
import org.springframework.stereotype.Service;
import java.util.List;
import com.yourpackagestructure.Parent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
#Service
public class Service{
private MongoTemplate mongoTemplate;
public Service(MongoTemplate mongoTemplate){
this.mongoTemplate = mongoTemplate;
}
public List<Parent> getParentList(String mapKey){
Query query = new Query();
query.addCriteria(Criteria.where("someMap." + mapKey).exists(true));
List<Parent> parents = mongoTemplate.find(query,Parent.class);
}
}

“ConverterNotFoundException” in Spring boot JPA

I want to get the SearchOutput data object by calling a query(#Query method) with natural joins of 3 tables. but when the query runs it shows an error.
I have tried to fetch the data in my spring boot controller class. But its not working because of the error
package com.example.mysqlproj.model;
import lombok.*;
public class SearchOutput {
private String hotel_name;
private String room_type;
private int price;
}
package com.example.mysqlproj.dao;
import com.example.mysqlproj.model.Room_Type;
import com.example.mysqlproj.model.SearchOutput;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.Collection;
import java.util.Date;
import java.util.List;
public interface RoomTypeDao extends CrudRepository<Room_Type,Integer> {
#Query(value="select new SearchOutput(hotel_name , room_type,(price*(?4)*(?3)*(1.15))) from Room_type natural join Hotel natural join True_contract where (?1 >= start_date and ?2 <= end_date and ?3 <=available_rooms and ?4<= max_adults )", nativeQuery = true)
List<SearchOutput[]> checkHotelList(Date from, Date to, int rooms, int adults, int total_nights);
}
The Error:
No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.mysqlproj.model.SearchOutput]] with root cause
My target is to fetch a searchOutput object array when the query gets called.
Are there any solutions for this. Thanks in advance
The response type from the query is
List<Map<String, Object>> .
Please change the method return type to this.

how can i display my data on jsp page in struts2

my action class is :-
package com.action;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.struts2.convention.annotation.*;
import org.apache.struts2.rest.DefaultHttpHeaders;
import com.opensymphony.xwork2.ActionSupport;
#ParentPackage(value="default")
#Namespace("/")
#ResultPath(value="/")
public class noOfUsers extends ActionSupport {
private static final long serialVersionUID = 1L;
#Action(value="usersn",results={
#Result(name="create",type="tiles",location="users")
})
public static DefaultHttpHeaders create(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("tujpa");
EntityManager em=emf.createEntityManager();
EntityTransaction entr=em.getTransaction();
entr.begin();
Query query=em.createQuery("SELECT U.firstname from User U");
List <User> list = query.getResultList();
System.out.println("password");
Iterator iterator = list.iterator();
System.out.println("password1");
while(iterator.hasNext()){
String empFirstName = (String)iterator.next();
System.out.print("Emp Name:"+empFirstName );
System.out.println("password2");
}
entr.commit();
em.close();
return new DefaultHttpHeaders("create");
}
}
and i want to display my result list on my jsp page,
so please guide.
thanks in advance.
Okay I can see why there has not been an answer... you've taken some JPA code which prints to the terminal and then pasted that into S2 class which you've found off the Internet?
Please start with a simple "Hello World" application: http://struts.apache.org/2.2.1.1/docs/getting-started.html
When that is running, there are plenty of examples of using the iterator tag. This tag goes on the JSP, and is documented on the above listed site.
Your action code then would become something like (quick hack job):
public class UserList extends ActionSupport {
List <User> list;
public String action(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("tujpa");
EntityManager em=emf.createEntityManager();
EntityTransaction entr=em.getTransaction();
entr.begin();
Query query=em.createQuery("SELECT U.firstname from User U");
list = query.getResultList();
em.close();
return SUCCESS;
}
}
Now you should research some DI framework... S2 has good Spring integration moving the EntityManagerFactory/EntityManager handling to Spring would make the above much cleaner. Something like:
public String action(){
list = em.createQuery("SELECT U.firstname from User U").getResultList();
return SUCCESS;
}

Categories