How not to clear the JPA cache? - java

How not to clear the JPA cache?
Code do Searching destination, poi2dicon, poi3dicon, destinationcategory with findByCode and findByName.
However, when executing the same parameter (findByCode("A")) in the for statement, the select statement is executed in the repository.
I know that the value corresponding to findByCode("A") exists in the cache of JPA.
Then, in the for statement, the query of findByCode("A") should be executed only once, but in reality, as many queries as rows.size are searched.
I wonder how to keep the value of findByCode("A") in the cache, and why the content of findByCode("A") is lost in the code now.
List<Destination> result = new ArrayList<>();
int headerLength = rows.get(0).size();
for (int i = 1; i < rows. size(); i++) {
Map<String, String> destinationMap = new HashMap<>();
makeDestinaionMap(destinationMap)
Destination findDestination = destinationRepository.findByCode(destinationMap.get("Identification Code"));
Poi2dIcon poi2dIcon = poi2dIconService.findByName(destinationMap.get("2DIcon")).get(0);
Poi3dIcon poi3dIcon = poi3dIconService.findByName(destinationMap.get("3DIcon")).get(0);
DestinationCategory destinationCategory = destinationCategoryService.findByName(destinationMap.get("Category")).get(0);
// builder -> save
Destination destination = Destination.builder()
...build()
if (findDestination != null) {
destination.setId(findDestination.getId());
}
result.add(destination);
}
destinationRepository.saveAll(result);
Best Regards

Related

getting Duplicate List Values in GET API service in spring Boot

i am getiing proper values from DB but Getting Duplicate List Values while add list object to class object, in Spring Boot
Please suggest to me how to do it.
Get data from DB Code : Here Rooms is my DB Entity class
CriteriaBuilder roomsBuilder = roomSession.getCriteriaBuilder();
CriteriaQuery<Rooms> query = roomsBuilder.createQuery(Rooms.class);
Root<Rooms> root = query.from(Rooms.class);
Predicate userRestriction = roomsBuilder.or(roomsBuilder.notEqual(root.get(SmatrEntityParameters.IS_DELETED), "Y"),
roomsBuilder.isNull(root.get(SmatrEntityParameters.IS_DELETED)));
Predicate userRestriction2 = roomsBuilder.and(roomsBuilder.equal(root.join("properties").get(SmatrEntityParameters.PROPERTY_ID), propertyId));
query.where(roomsBuilder.and(userRestriction, userRestriction2));
Query q = roomSession.createQuery(query);
List<Rooms> getroomslistobj= q.getResultList();
Iterate the list code: Here getAllRoomsobj means main response pojo class
List<GetAllRooms> getallroomslistobj = new ArrayList<GetAllRooms>();
for (int i = 0; i < getroomslistobj.size(); i++) {
int dbroomId = getroomslistobj.get(i).getRoomId();
String dbroomName = getroomslistobj.get(i).getRoomName();
// Actual code start
getAllRoomsobj.setRoomId(dbroomId);
getAllRoomsobj.setRoomName(dbroomName);
getallroomslistobj.add(getAllRoomsobj);
// Actual code end
}
I tried one code at the middle of the Actual code but I did not want create a new object for the response class:
GetAllRooms object = new GetAllRooms();
object.setRoomId(dbroomId);
object.setRoomName(dbroomName);
getallroomslistobj.add(object);
Please Help me Out,
Thanks in Advance
u can try it by stream.map() of java8

Lucene index: getting empty result while query

I am trying to query with Lucene index but getting the empty result and below errors in the log,
Traversal query (query without index): select [jcr:path] from [nt:base] where isdescendantnode('/test') and name='World'; consider creating an index
[async] The index update failed
org.apache.jackrabbit.oak.api.CommitFailedException: OakAsync0002: Missing index provider detected for type [counter] on index [/oak:index/counter]
I am using RDB DocumentStore and I have checked index and node are created in nodes table.i tried below code,
#Autowired
NodeStore rdbNodeStore;
//create reposiotory
LuceneIndexProvider provider = new LuceneIndexProvider();
ContentRepository repository = new Oak(rdbNodeStore)
.with(new OpenSecurityProvider())
.with(new InitialContent())
.with((QueryIndexProvider) provider)
.with((Observer) provider)
.with(new LuceneIndexEditorProvider())
.withAsyncIndexing("async",
5).createContentRepository();
//login reposiotory and retrive session
ContentSession contentSession = repository.login(null, null);
Root root = contentSession.getLatestRoot();
//create lucene index
Tree index = root.getTree("/");
Tree t = index.addChild("oak:index");
t = t.addChild("lucene");
t.setProperty("jcr:primaryType", "oak:QueryIndexDefinition", Type.NAME);
t.setProperty("compatVersion", Long.valueOf(2L), Type.LONG);
t.setProperty("type", "lucene", Type.STRING);
t.setProperty("async", "async", Type.STRING);
t = t.addChild("indexRules");
t = t.addChild("nt:base");
Tree propnode = t.addChild("properties");
Tree t1 = propnode.addChild("name");
t1.setProperty("name", "name");
t1.setProperty("propertyIndex", Boolean.valueOf(true), Type.BOOLEAN);
root.commit();
//Create TestNode
String h = "Hello" + System.currentTimeMillis();
String w = "World" + System.currentTimeMillis();
Tree test = root.getTree("/").addChild("test");
test.addChild("a").setProperty("name", Arrays.asList(new String[] { h, w }), Type.STRINGS);
test.addChild("b").setProperty("name", h);
root.commit();
//Search
String query = "select [jcr:path] from [nt:base] where isdescendantnode('/test') and name='World' option(traversal ok)";
List<String> paths = executeQuery(root, query, "JCR-SQL2", true, false);
for (String path : paths) {
System.out.println("Path=" + path);
}
can anyone share some sample code on how to create Lucene index?
There are a couple of issues with what you're likely doing. First thing would the error that you're observing. Since you're using InitialContent which provisions an index with type="counter". For that you'd need to have .with(new NodeCounterEditorProvider()) while building the repository. That should avoid the error you are seeing.
But, your code would likely still not work because lucene indexes are async (which you've correctly configured). Due to that asynchronous behavior, you can't query immediately after adding the node.
I tried your code but had to add something like Thread.sleep(10*1000) before going for querying.
As another side-note, I'd recommend that you try out IndexDefinitionBuilder to make lucene index structure. So, you could replace
Tree index = root.getTree("/");
Tree t = index.addChild("oak:index");
t = t.addChild("lucene");
t.setProperty("jcr:primaryType", "oak:QueryIndexDefinition", Type.NAME);
t.setProperty("compatVersion", Long.valueOf(2L), Type.LONG);
t.setProperty("type", "lucene", Type.STRING);
t.setProperty("async", "async", Type.STRING);
t = t.addChild("indexRules");
t = t.addChild("nt:base");
Tree propnode = t.addChild("properties");
Tree t1 = propnode.addChild("name");
t1.setProperty("name", "name");
t1.setProperty("propertyIndex", Boolean.valueOf(true), Type.BOOLEAN);
root.commit();
with
IndexDefinitionBuilder idxBuilder = new IndexDefinitionBuilder();
idxBuilder.indexRule("nt:base").property("name").propertyIndex();
idxBuilder.build(root.getTree("/").addChild("oak:index").addChild("lucene"));
root.commit();
The latter approach, imo, is less error prone and more redabale.

Getting data in a Geode Server with a Partitioned Region

I have a Geode system with one locator, three cache servers and one client. Inside these servers, there is a partitioned region which my data is in. What I am trying to do is that run a function on each server to get the data on that specific server. I wrote the function below for beginning:
public void execute(FunctionContext fc) {
Cache cache = CacheFactory.getAnyInstance();
// testRegion is a partitioned region
Region<Object, Object> region = cache.getRegion("/testRegion");
Set<Object> keys = region.keySet();
Set keysTillSecondLast = new HashSet();
int setSize = keys.size();
Iterator keysIterator = keys.iterator();
for(int i = 0; i < (setSize -1); i++)
{
keysTillSecondLast.add(keysIterator.next());
}
for (Object k : keysTillSecondLast) {
fc.getResultSender().sendResult((Serializable) region.get(k));
}
Object lastResult = keysIterator.next();
fc.getResultSender().lastResult((Serializable) region.get(lastResult));
}
There are 30 entries in the partitoned region. When I call the function above like this:
public void runFunction() {
MyFunction function = new MyFunction();
FunctionService.registerFunction(function);
Execution execution = FunctionService.onServers(cache);
ResultCollector collector = execution.execute(new MyFunction());
List result = (List) collector.getResult();
System.out.println(result);
}
The result list's size is 60 (duplicate entries). When I use FunctionService.onServer() method instead, than the list size is 30 which is all the data I have pushed. So is there a way to get only the data on a specific server? Like when I run the function it should return something like:
Data on Server1: ....
Data on Server2: ....
Data on Server3: ....
You need to use PartitionRegionHelper in your function body to get the local data. Something like:
#Override
public void execute(FunctionContext context) {
RegionFunctionContext rfc = (RegionFunctionContext) context;
Region r = PartitionRegionHelper.getLocalDataForContext(rfc);
...
}

how to get data from database by sending a list?

Could someone help me out ow to get data from a table in the database by sending a list.
`
List<CampaignStructure> campIdList = new ArrayList<>(); try {
JSONArray clientjson = new JSONArray(campaignids);
Set<Long> list = new HashSet<>();
for(int i = 0; i < clientjson.length(); i++){
list.add(Long.parseLong(clientjson.getJSONObject(i).getString("id")));
}
for(Long id: list){
CampaignStructure c = new CampaignStructure();
c.setCampaignId(id);
campIdList.add(c);
}
} catch (JSONException e) {
}
Here campaignids contains list of ids (can contain duplicates).
campIdList contains distinct ids. i want to send these ids and get the data from database.
findByCampaignIdIn(List campIdList) should work.
You can find all list of JPA repository keywords can be found in the current documentation listing.
It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.

neo4j Java beginner. Cypher Execution Engine

The user logs in on the website and creates different events. This event is saved into the neo4j database as a node and I make the "EVENT_CREATOR" realtionship between the user and the event node.
I am trying to implement pagination for all the user's events on my website (using Play2 framework) and I need for example if user accesses the first page, I load the first ten events; 2nd page to load the 10th- 20th events, and so on...
this is my query:
match(n);
...
skip k;
limit 10;
return n;
At the moment I am getting all the events created by the user and add them to the array list.
private static List<PublicEvent> getEvents(int page, int pageSize) {
List<PublicEvent> events = new ArrayList<PublicEvent>();
GraphDatabaseService db = Neo4JHelper.getDatabase();
try (Transaction tx = db.beginTx()) {
Index<Node> userIndex = db.index().forNodes(ModelIndex.Users);
IndexHits<Node> userNodes = userIndex.get(ModelGraphProperty.UserProfile.UserName, SessionUtilities.getCurrentUser());
Node me = userNodes.next(); //current logged in user
PagingIterator paginator = new PagingIterator(me.getRelationships(GraphRelation.RelTypes.EVENT_CREATOR).iterator(), pageSize); // get all the events that were created by this user
paginator.page(page);
// adding all the created events by this user to an array
if (paginator.hasNext()) {
Relationship eventCreator = (Relationship)paginator.next();
Node event = eventCreator.getOtherNode(me);
events.add(new PublicEvent(event));
}
tx.success();
}
db.shutdown();
return events;
}
I want to update the code to run Cypher queries and I add the following lines of code (using the example https://www.tutorialspoint.com/neo4j/neo4j_cypher_api_example.htm )
GraphDatabaseService db = Neo4JHelper.getDatabase();
ExecutionEngine execEngine = new ExecutionEngine(db); //HERE I GET AN ERROR
ExecutionResult execResult = execEngine.execute("MATCH (n) RETURN n");
String results = execResult.dumpToString();
System.out.println(results);
it is expecting a second parameter: logger. What is the error or is there anything I am doing wrong?
RestGraphDatabase db= (RestGraphDatabase)Neo4JHelper.getDatabase();
RestCypherQueryEngine engine=new RestCypherQueryEngine(db.getRestAPI());
Map<String, Object> params = new HashMap<String, Object>();
params.put( "id", eventId );
String query="match (s) where id(s) = {id} return s;";
QueryResult result=engine.query(query,params);
if(result.iterator().hasNext()) {
//HERE PUT WHATEVER YOU NEED
}
Take a look at the documentation:
https://neo4j.com/docs/java-reference/current/

Categories