How does this query method work? - spring-data-neo4j

#Query("MATCH (m:Movie)<-[r:ACTED_IN]-(a:Person) RETURN m,r,a LIMIT {limit}")
Collection<Movie> graph(#Param("limit") int limit);
For this query, it's returning "RETURN m, r, a", which is a full subgraph with 3 elements. Then why the return value of 'graph' method is a collection of "Movie" only? Where is the 'r, a' which is also returned.
I am trying to understanding the mechanism behind the scene.

It seems that you have a #RelationshipEntity defined in your class path but do not use it when defining #Relationships in the domain classes.
Sample:
#NodeEntity
class Pet {
// ...
}
#NodeEntity
class Person {
#Relationship(type = "HAS")
private List<Pet> pets;
// ...
}
#RelationshipEntity(type = "HAS")
class HasRelationship {
// ...
}
If Neo4j OGM, that acts behind the scenes of SDN, finds a relationship type, it looks for #RelationshipEntity first and if it finds them, tries to map the returned types back to the #NodeEntity. In this case OGM finds HasRelationship and wants to map it to the Person class. This fails because Person does only know of Pet and the objects get discarded.
Like my answer on GitHub.

Related

instance creating instances

How can I create an instance which creates as many instances as I want?
I think I have to create a class Manager for example and inside that class with an aggregation relationship to create the class name salary and bottles.
I want to create an instance of Manager which creates as many instances of bottle and salary I want. How can I do that?
It's called a factory and it looks something like:
class Factory {
Product create(int n);
// ...
}
class Product {
// ...
}
class Prod1 : public Product {
// ...
}
int main() {
Factory factory = Factory();
Product prod[10] = factory.create(10);
// ...
with create simply returning a Product object of some derived type. Of course, there's usually some context passed into the Factory::create function to hint at the type of Product you want.
Use pointers. You can have a pointer which points to as many instances as you want and new them whenever you want.

Partial Mock or new class or what else?

I have a question about testing.
I have a class that returns anomalies. in this class I have two different method that simply returns two different types of anomalies and one that return all anomalies (of both types)
this is the example code:
public interface IAnomalyService
{
IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2);
IList<Anomaly> GetAnomalies_OfTypeA(object parameter1);
IList<Anomaly> GetAnomalies_OfTypeB(object parameter2);
}
public class AnomalyService : IAnomalyService
{
public IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2)
{
var lstAll = new List<Anomaly>();
lstAll.AddRange(GetAnomalies_OfTypeA(parameter1));
lstAll.AddRange(GetAnomalies_OfTypeB(parameter2));
return lstAll;
}
public IList<Anomaly> GetAnomalies_OfTypeA(object parameter1)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 1 } };
}
public IList<Anomaly> GetAnomalies_OfTypeB(object parameter2)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 2 } };
}
}
class Anomaly
{
public int Id { get; set; }
}
I've created the tests for the two method that retrieve the anomalies of type A and type B (GetAnomalies_OfTypeA and GetAnomalies_OfTypeB).
Now I want to test the function GetAllAnomalies but I'm not sure what I have to do.
I think I have to way for testing it:
1) declare GetAnomalies_OfTypeA and GetAnomalies_OfTypeB in class AnomalyService as virtual, make a mock of the Class AnomalyService, and using Moq I can set CallBase as true and mock the two method GetAnomalies_OfTypeA and GetAnomalies_OfTypeB.
2)move the method GetAllAnomalies in another class called AllAnomalyService (with interface IAllAnomalyService) and in its constructor I will pass an interface of IAnomalyService and after I can test the GetAllAnomalies mocking the IAnomalyService interface.
I'm new at unit testing, so I don't know which solution is better, if is one of the mines or another one.
Can you help me?
thank you
Luca
Mocking is a good tool when a class resists testing. If you have the source, mocking is often not necessary. Try this approach:
Create a factory which can return AnomalyServices with various, defined anomalies (only type A, only type B, both, none, only type C, ...)
Since the three types are connected in some way, you should check all three in each test. If only anomalies of type A are expected, you should check that GetAllAnomalies returns the same result as GetAnomalies_OfTypeA and GetAnomalies_OfTypeB returns an empty list.

Sort a list based on URL parameter (or sort nested domain model in query)

I'm sure there is a way to do this, but I'm really stuck on this one.
I have a domain model that connects to entities Foo and Bar in a many-to-many-relationship. Now when I want to list all Foos to a certain Bar, I do the query and get a lot of FooBar objects. I iterate through these objects and add all Foos to a list.
Like so:
def fooBarRelations = FooBar.findAllByBar bar
def fooList = []
fooBarRelations.each { fooList.add it.foo }
How can I sort the fooList based upon the parameters a g:sortableColumn adds to the url namely sort (the field to sort) and order.
I know you can pass the parameters to the query directly but I think this is not possible in my case?
So how can I either
Make one query without list iterating so I can pass in the sorting parameters OR
Sort my custom list based upon the sorting parameters?
Addition 1 (03/25/2012)
If I could to this ...
def fooBarRelations = FooBar.findAllByBar bar, [sort: 'foo.' + params.sort, order: params.order]
... the problem would be solved. But passing this to the query does not have any effect on the output. Is there any way I can sort a query by a sub-property?
If you really can't sort within the query itself. Then you need a list of lists.
List<List<Fields>> mylist;// where List<Fields> is a lists of the fields.
Then use a Comparator to sort your List> by the desired filed. Say your desired field is at index 3:
new Compare(List<Fields> L1, List<Fields> L2){
if(L1.get(3)>L2.get(3))
return -1;//etc.
UPATE BASED ON COMMENT:
say your entity is as follows
public class Entity{
String name, address, school;
Integer bankaccount;
//etc...
}
Then
public class WhereISort{
List<Entity> myList;
String mysorter;//mysorter can be declared here as static final
public WhereISort(){//maybe pass list in here or whatever
}
public Response myWebService(params..., String sorter){
mysorter=sorter;//mysorter can be declared here as static final
Collections.sort(myList, new Comparator() {
public int compare(Entity e1, Entity e2) {
if(mysorter.equalsIgnoreCase("name")){
return e1.getName().compareToIgnoreCase(e1.getName());
}else if(mysorter.equalsIgnoreCase("bankaccount")){
//your code here, etc.
}
}
});
}
}
Of course, the main point is using "mysorter" and the inner class "Comparator" to sort

Why is my IQueryable LINQtoObject being treated as LINQtoSQL and throwing no supported translation to SQL

I have a LINQ dbml class that I am wrapping in a POCO. I have built overloaded constructors that take the DBML class and init. the wrapper objects properties based on the dbml object passed in.
For example
public class MyPerson{
public MyPerson(DBMLPerson p)
{
this.ID = p.ID;
this.Name = p.Name;
}
}
if I then do something like this where I return an IQueryable
{
return from p in datacontext.DBMLPerson
select new MyPerson(p){};
}
When I try to do further queries on that Iquearble I get "System.NotSupportedException: The member 'MyPerson.ID' has no supported translation to SQL.."
However if I do this
{
return from p in datacontext.DBMLPerson
select new MyPerson(){
ID = p.ID;
Name = p.Name;
};
}
I don't get an error at all and everything works perfect. Basically I want to have my class handle the conversion from LINQ object to POCO itself.
Basically I have to use the Object Initializer or I am unable to match on that field.
Ok not sure this will actually help anyone but but myself but my whole problem is the I shouldn't be using IQuerable after a certain point(outside of my repository)
iqueryable-can-kill-your-dog-steal-your-wife-kill-your-will-to-live-etc

Code Design / Testability How To?

My team is designing a library that is wrapping calls to Active Directory to search and return a list of people.
We have a person class that wraps up the information for a person found. We then use the List to wrap them up. When we call the search it uses the internal System.Directory library and returns a SearchResultCollection object. We then iterate through it to build up the list<> and return that.
We have designed the person class to only have read only (get) properties since we don't want the callee to change the person info. We pass in the SearchResult object from the System.Directory library on the constructor of the person.
My issue is we can't test this easily.
My thoughts so far have been:
Pass variables into the person constructor for each property needing to be set.
Unfortunately, this will make for a very long constructor parameter list.... Smells bad to me.
Allow the person class to have setters on the properties.
Again, smells bad to me since we can't control the callee from using this.
Refactor:
I have looked at the extract to interface and adapt parameter techniques. It seems the adapt parameter has the most promise? Adapt parameter seems nice because it does help break the dependency I have on the Directory Library's SearchResult object. So if in the future I wanted to do some other kind of search we are in good shape. At least I think we are?
Sub class the person object and create a test Person with setters....
Seems like it would work but not sure if it's the right way to go?
Mock it
Haven't done any mocking yet so again not sure on this one.
EDIT: If mocking is best idea please let me know... However, I would be interested to know how this would be done without mocking also (or perhaps it really isn't do able without mocking)....
I would appreciate guidance on this one.
Here's a snippet of the code:
public class PeopleSearcher
{
.... declarations left out....
public List<Person> FindPerson(string FirstName, string LastName, string Login)
{
...filter setup left out for brevity....
_peopleFound = _directoryToSearch.FindAll();
//Convert to list of persons....
int cnt = 0;
_listOfPeople = new List<Person>();
while (cnt < _peopleFound.Count)
{
Person p = new Person(_peopleFound[0]);
_listOfPeople.Add(p);
cnt++;
}
return _listOfPeople;
}
}
public class Person
{
private string sn;
....further declarations left out for brevity....
public Person(SearchResult PersonFound)
{
sn = PersonFound.Properties["sn"].Count == 0 ? string.Empty : PersonFound.Properties["sn"][0].ToString();
givenName = PersonFound.Properties["givenName"].Count == 0 ? string.Empty : PersonFound.Properties["givenName"][0].ToString();
sAMAccountName = PersonFound.Properties["sAMAccountName"].Count == 0 ? string.Empty : PersonFound.Properties["sAMAccountName"][0].ToString();
adsPath = PersonFound.Path == null ? string.Empty : PersonFound.Path;
}
public string LastName
{
get
{
return sn;
}
}
.... more getters...
}
}
"Mocking" is a word that is usually used for all kinds of test doubles. And most times people or not "mocking", they're faking or stubbing. Anyway, your 4th option (subclass and add setters) sounds to me like the easiest way to go given your codebase assuming you want Person objects to pass toother methods. Because I don't think you're talking about testing that the person object gets the properties set correct by the constructor, right?
Mock it. This is the sort of situation that mocking was invented for. I've only done mocking in Ruby, so I'm not sure of the state of the art for .net, but it should work well.
When mocking it you might realize some areas that should be refactored. This is also a good plan.
In your mock (by framework or otherwise), you're still going to end up having to create Person objects with values, which leads you right back to your original problem.
Fortunately, there are two excellent solutions:
1) Go ahead and add setters to the Person class, but make them protected. This means your mock and test code would have to be in the same package, but would block other users from mutating your Persons. (and we don't want mutants running around - there's been enough of that in the movies lately).
2) Use a Builder class (as Joshua Bloch describes in Effective Java). You'd create a public static PersonBuilder class inside Person, which would export a build method and chainable parameter specifiers (like setters, but not separately callable):
public class Person ....
public static class PersonBuilder {
public PersonBuilder (String firstName, String lastName) {...} // my sample has two required values
public Person build() { ... }
public PersonBuilder ssn (String value) { ... }
public PersonBuilder adsPath (String value) { ... }
...
}
...
}
The chainable value specifiers look like this:
public PersonBuilder ssn (String value) {
this.sn = value;
return this;
}
Then a call to create a Person looks like this:
Person thisPerson = new Person.PersonBuilder ("John", "Smith").ssn("123-45-6789").adsPath("whatever");
This method completely hides the methods which can set the values (indeed, you have no "setters"), but keeps you from having to deal with long constructor argument lists (which makes it easier to deal with optional values).
Incidentally, you also probably want to make Person's constructor private.