Neo4j: spring-data-neo4j,how to cast result to my type class? - casting

I have insert some node into Neo4j DB.And I want to select some node from database and cast it to specific class.
Here are some code about the problem:
class Service {
Neo4jTemplate neo4jTemplate
#Transactional
def find() {
def id1 = 11
//Knowledge k = neo4jTemplate.findOne(1, Knowledge)
Result result = neo4jTemplate.query("start n=node(11) return ID(n),n.name,n.age;", null)
//how to cast the result to User class
println "the tpye of result called User is "+ result.to(User.class).is(cn.edu.bnuz.itc.bok.sub2.User.class)
}
}
The detail about node like :
+-------------------------------------------------------------------------+
| Node[11]{career:"programmer",name:"kelvin",age:35,introduce:"lazy doy"} |
+-------------------------------------------------------------------------+
#NodeEntity
class User {
#GraphId
Long id;
String name;
int age;
}
I just want get the node's id, name, age from db and put it into a User class.
But it failed many time with many method.
Here I have encounter a problem which is :How can I cast the result to my target class? I have try many method to cast but fail finally.Thank you for you attention.

Return the user node from the query and call the to method of the returned Result with the desired class as argument:
Result result = neo4jTemplate.query("start n=node(11) return n", null);
for(User u : result.to(User.class)) {
doSomethingWith(u);
}
You may want to consider using repositories that support cypher queries like:
public interface UserRepository extends GraphRepository<User> {
#Query("start n=node(11) return n")
Iterable<User> getUser11();
}

Related

How to test an Update class in apex

Hello I am new to apex and soql, I would like some help on my test class, below is the code i am having trouble with,
public class UpdateMyCard {
#AuraEnabled(cacheable=false)
public static Card__c updateCard(Double Amount){
String userId = UserInfo.getUserId();
Card__c myCard = [SELECT Id, Card_no__c, total_spend__c From Card__c Where OwnerId =:userId];
myCard.total_spend__c = myCard.total_spend__c + Amount;
try{
update myCard;
}catch (Exception e) {
System.debug('unable to update the record due to'+e.getMessage());
}
return myCard;
}
}
Test Class
#isTest
public static void updatecard(){
UpdateMyCard.updateCard(200);
}
Error:
System.QueryException: List has no rows for assignment to SObject
Your code assumes there's already a Card record for this user. And it's exactly 1 record (if you have 2 your query will fail). I'm not sure what's your business requirement. Is it guaranteed there will always be such record? Should the code try to create one on the fly if none found? You might have to make that "updateCard" bit more error-resistant. Is the total spend field marked as required? Because "null + 5 = exception"
But anyway - to fix your problem you need something like that in the test.
#isTest
public static void updatecard(){
Card__c = new Card__c(total_spend__c = 100);
insert c;
UpdateMyCard.updateCard(200);
c = [SELECT total_spend__c FROM Card__c WHERE Id = :c.Id];
System.assertEquals(300, c.total_spend__c);
}

Spring Data Neo4j Map query result to Non entity POJOs

I am using spring-data-neo4j. I want the results of the query to be mapped to a non-entity POJO.
This is how the repository looks like
public interface CategoryRepository extends GraphRepository<Category> {
#Query("Match (:Client {email: {clientEmail}})-[:client]->()" + "-[:owns]->()-[:had]->(a:visit)-[:to]->()-[:category]->(b)"
+ " where a.lastPredictionTime > {startTime} and a.lastPredictionTime < {endTime}" + " with Distinct b.name as category, sum(a.timeSpent) as sum order by sum desc"
+ " return collect({category: category, timeSpent: sum})[{start}..{end}]")
List<CountDetailsByDate> getTopCategoriesByTimeSpent(#Param("clientEmail") String clientEmail, #Param("start") int start, #Param("end") int end,
#Param("startDate") long startDate, #Param("endDate") long endDate);
}
The CountDetailsByDate object is neither a node entity nor a relationship entity, I want the result of the query to be mapped to it. Is there any way to do that?
You should create a CountDetailsByDate class and annotate it with #QueryResult.
You can either define it as an inner class in your CategoryRepository repository interface or you can create it somewhere else.
The inner-class code will be like this :
public interface CategoryRepository extends GraphRepository<Category> {
#Query("Match (:Client {email: {clientEmail}})-[:client]->()" + "-[:owns]->()-[:had]->(a:visit)-[:to]->()-[:category]->(b)"
+ " where a.lastPredictionTime > {startTime} and a.lastPredictionTime < {endTime}" + " with Distinct b.name as category, sum(a.timeSpent) as sum order by sum desc"
+ " return collect({category: category, timeSpent: sum})[{start}..{end}]")
List<CountDetailsByDate> getTopCategoriesByTimeSpent(#Param("clientEmail") String clientEmail, #Param("start") int start, #Param("end") int end,
#Param("startDate") long startDate, #Param("endDate") long endDate);
}
#QueryResult
class CountDetailsByDate {
// class variables and ...
}
If you choose to create a separate class , make sure you add the package path to component scan of your Neo4j Config class. It will be something like this :
#Configuration
#EnableTransactionManagement
#EnableNeo4jRepositories(basePackages = {"XXX-PATH-TO-Repo-packages"})
#ComponentScan(basePackages = "YYY-PATH-TO-YOUR-CLASS-Package")
public class Neo4jConfig extends Neo4jConfiguration {
....
}
Hope this will help.

Neo4j Spring Data Query Builder

Is there a way of dynamically building a cypher query using spring data neo4j?
I have a cypher query that filters my entities similar to this one:
#Query("MATCH (n:Product) WHERE n.name IN {0} return n")
findProductsWithNames(List<String> names);
#Query("MATCH (n:Product) return n")
findProductsWithNames();
When the names list is empty or null i just want to return all products. Therefore my service impl. checks the names array and calls the correct repository method. The given example is looks clean but it really gets ugly once the cypher statements are more complex and the code starts to repeat itself.
You can create your own dynamic Cypher queries and use Neo4jOperations to execute them. Here is it an example (with a query different from your OP) that I think can ilustrate how to do that:
#Autowired
Neo4jOperations template;
public User findBySocialUser(String providerId, String providerUserId) {
String query = "MATCH (n:SocialUser{providerId:{providerId}, providerUserId:{providerUserId}})<-[:HAS]-(user) RETURN user";
final Map<String, Object> paramsMap = ImmutableMap.<String, Object>builder().
put("providerId", providerId).
put("providerUserId", providerUserId).
build();
Map<String, Object> result = template.query(query, paramsMap).singleOrNull();
return (result == null) ? null : (User) template.getDefaultConverter().convert(result.get("user"), User.class);
}
Hope it helps
Handling paging is also possible this way:
#Test
#SuppressWarnings("unchecked")
public void testQueryBuilding() {
String query = "MATCH (n:Product) return n";
Result<Map<String, Object>> result = neo4jTemplate.query(query, Collections.emptyMap());
for (Map<String, Object> r : result.slice(1, 3)) {
Product product = (Product) neo4jTemplate.getDefaultConverter().convert(r.get("n"), Product.class);
System.out.println(product.getUuid());
}
}

adding an object to a list in play framework

I am new to play, whenever I use list.add(Object) to the list and print the size of the list, it remains 0 !!!
My Method is to like a tutorial, it checks if the logged-in user has liked this tutorial before, if yes, it increments the likeCount of the tutorial by one, and add the tutorial to the like list of the user. If no, it renders that he already likes it.
since the tutorial is not saved in the list, I am not able to check if it is already liked or not !!!
Models:
#Entity
public class RegisteredUser extends Model {
public String name;
#ManyToMany
public List<Tutorial> contributedTutorials;
public RegisteredUser(String name) {
this.name = name;
this.likeList = newArrayList<Tutorial>();
this.save();
}
}
#Entity
public class Tutorial extends Model {
public String Title;
public int likeCount;
public Tutorial(String title) {
this.title = title;
this.likeCount = 0;
}
Controller:
public Tutorials extends Controller {
public static void likeTutorial() {
if (session.get("RegisteredUserId") != null && session.get("tutID") != null ) {
{
long uId = Long.parseLong(session.get("RegisteredUserId"));
RegisteredUser user = RegisteredUser.findById(uId);
long tId = Long.parseLong(session.get("tutID"));
Tutorial tut = Tutorial.findById(tId);
int x = tut.likeCount;
x++;
if (!(user.likeList.contains(tut)))
// to check that this user didn't like this tut before
{
Tutorial.em().createQuery("update Tutorial set likeCount ="+ x +" where id=" +tId).executeUpdate();
tut.refresh();
user.updateLikeList(tut); // THIS IS NOT WORKING!!!
renderText("You have successfully liked this Tutorial " + user.likeList.size());
}
}
renderText("Opps Something went Wrong!!");
}
}
}
The view :
Like
+You don't need to call the this.save() and this.likeList = newArrayList<Tutorial>(); in the constructor. Actually the latter is syntactically wrong.
+Passing the tutorial ID as a session variable is very wrong. You need to pass it as a GET parameter to the action.
+Replace your check with:
// to check that this user didn't like this tut before
if (! user.likeList.contains(tut)) {
// Tutorial.em().createQuery("update Tutorial set likeCount ="+ x +" where id=" +tId).executeUpdate();
// tut.refresh();
// user.updateLikeList(tut); // THIS IS NOT WORKING!!!
tut.likeCount++;
tut.save();
// Since it's a ManyToMany relationship, you only need to add it to one list and the other will reflect properly if mappedBy properly
user.likeList.add(tut); // note that the example you showed uses contributedTutorials not likeList
user.save();
renderText("You have successfully liked this Tutorial " + user.likeList.size());
}
I made all adjustments You mentioned above
And
The mapping in RegisteredUser Model
#ManyToMany
public List<Tutorial> likeList;
and I have added the mapping to Tutorial Model
#ManyToMany
public List<RegisteredUser> likersList;
and adjusted the method in the controller as follows
if (! user.likeList.contains(tut)) {
tut.likeCount++;
//tut.likersList.add(user); // however this raised an error too! at the next line
tut.save();
//as for the likeCount update, it has worked perfectly, Thank You
// Since it's a ManyToMany relationship, you only need to add it to one list and the other will reflect properly if mappedBy properly
//I have modified Model Tutorial as shown above and it didn't work too !
user.likeList.add(tut);
user.save(); // this raised an error!!
renderText("You have successfully liked this Tutorial " + user.likeList.size());
}

Why does my XML ASP.NET web service return results which repeats itself?

I have written an ASP.NET web service.
It looks like this:
WebServices.logic pLogic = new WebServices.logic();
WebServices.manager[] pManager = new PowerManager[1];
pManager[0] = new PowerManager();
pManager[0].CustomerId = "sjsjshd";
pManager[0].state = pLogic.getState("sasj");
return pManager[0];
The pManager class looks like this:
public string _CustomerId;
public int PowerStatus;
public List<ArrayList> _Power;
public string CustomerId
{
get
{
return _CustomerId;
}
set
{
_CustomerId = value;
}
}
public List<ArrayList> Power
{
get
{
return _Power;
}
set
{
_Power = value;
}
}
When I run it, I get a repetition of the results, like so:
<p>
<_CustomerId>sjsjshd</_CustomerId>
<pStatus>0</PowerStatus>
−
<_p>
−
<ArrayOfAnyType>
<anyType xsi:type="xsd:int">1</anyType>
</ArrayOfAnyType>
<ArrayOfAnyType/>
</_p>
<CustomerId>sjsjshd</CustomerId>
−
<p>
−
<ArrayOfAnyType>
<anyType xsi:type="xsd:int">1</anyType>
</ArrayOfAnyType>
<ArrayOfAnyType/>
</p>
</pManager>
However, there is no duplicate values stored (Eg. I store client name in a collection, but only once - count of 1). There are no duplicates stored when I call getState(). This method returns a collection and it contains one value, but the results in XML has a repetition of this.
How comes the results appear to repeat themselves? When running the system, I only get one error.
Thanks
OK, looks like your XML serialization is giving you all the public members of your PowerManager class. Based on the naming convention of starting with an underscore, those members should be private, like this:
private string _CustomerId;
private List<ArrayList> _Power;
You also state "When running the system, I only get one error." What error are you getting?