I am using spring-data-neo4j V4 and look for solution how to fetch entities which are not directly connected to the loaded entity. To explain:
I do have 3 entities in my neo4j database.
#NodeEntity(label="membership")
public class Membership extends AbstractEntity{
public Membership(){ }
private String membershipId;
#Relationship(type = "IN_YEAR", direction = Relationship.OUTGOING)
private Set<Year> year = new HashSet<>();
//getter+setter
}
#NodeEntity(label="year")
public class Year extends AbstractEntity{
public Year(){}
private String name;
private String membershipId;
#Relationship(type = "IN_MONTH", direction = Relationship.OUTGOING )
private Set<Month> month = new HashSet<>();
//getter+setter
}
#NodeEntity(label="month")
public class Month extends AbstractEntity{
private String name;
//getter+setter
}
When i call my MembershipRepository and load a Membership by Id:
membershipRepository.findByMembershipId(id);
the year entities will be fetched but the month entities not.
Can anybody tell what is the best or recommended way to load the month entities when loading the membership entity? As written in http://docs.spring.io/spring-data/neo4j/docs/current/reference/html/ the #Fetch is obsolete since version 4 so I need another solution.
EDIT:
I read in http://docs.spring.io/spring-data/neo4j/docs/current/reference/html/ the workaround for fetch, just use the load methods from the Neo4jTemplate.
So I load the months for every year by:
Set<Year> fetchedYear = new HashSet<>();
for(Year year : ms.getYear()){
fetchedYear.add(neo4jTemplate.load(Year.class, year.getId(), 1));
}
ms.setYear(fetchedYear);
But is there a better solution?
The first option would be to use loadByProperty and set the loading depth to 2.
Example:
neo4jTemplate.loadByProperty(Membership.class, "membershipId", value, 2);
This is available for SDN-4.1.0-Snapshot
But if you do not want to load a Membership with depth 2 because too much of your graph will be loaded (from other relationships) then I think you could construct a cypher query (using OPTIONAL MATCH), execute it with the neo4jTemplate and retrieve the Object which will then be automatically mapped due to the “smartObjectMapping".
Example:
String query = "MATCH (n:Membership{membershipId:{id})-[r]-(m) OPTIONAL MATCH (m:Year)-[e]-(x) RETURN n,r,m,e,x";
Map<String,Object> map = new HashMap<>();
map.put("id",value);
Result result = neo4jTemplate.query(query,map);
now n in the Result should contain all mapped relationships
Related
I am new to MongoDB and have trouble. I would be very grateful if someone could help me with it.
I have the entity like:
class FileRecord {
private ObjectId id;
private String fileId;
private EnumStatus status;
private Long userId;
private Integer year;
etc.
> }
A file can have many records but only one in the year.
I need to get all the last documents by criteria.
I don't understand how to make it right in Spring, but in the mongo query too if to be honest)
I understand how to make criteria for it:
var match = match(Criteria.where("userId").in(userIds).andOperator(Criteria.where("status").in(EnumStatus.availableStatues())));
And group by max:
var group = group("fileId", "year").max("year").as("max_year");
But how to make it to query in one that will return for me Colletion<FileRecord> after aggregation?
If I try it make it this way:
var aggregation = newAggregation(filter, group);
AggregationResults<FileRecord> aggregateResult =
mongoOperations.aggregate(aggregation, FileRecord.class, FileRecord.class);
Collection<FileRecord> records = aggregateResult.getMappedResults()
I get an exception:
readObjectId can only be called when CurrentBSONType is OBJECT_ID, not when CurrentBSONType is DOCUMENT.;
If someone has an idea I'm interested
Thank you in advance
I found the answer)
var group = group("fileId", "year").max("year").as("max_year").first("_id").as("enityId");
I needed to create the projection and after again make request to the DB and get the data that I needed by id. I don't have many of them, so the solution worked for me. But, as I understand, you can add a lot "first", and add the fields you need. And get all by one request
I am working on a dynamic filter component based on QueryDSL with the use of SpringData for query execution. Thus I create Predicate instances from the received data ad pass it to QueryDslPredicateExecutor. For dynamic access to entity attributes I use generic PathBuilder typed to the entity class.
Consider the following (simplified) code:
class Offer {
List<LanguageToName> names;
}
class LanguageToName {
String name;
String language;
}
When I try to query Offer entites, that have in their collection name element with attribute 'abc', I simply create the predicate as follows:
pathBuilder.getCollection("names", LanguageToName.class).any().getString("name")
.like("%" + fieldData.getFieldValue() + "%");
However, I was unable to come up with a solution to filter the collection by multiple attributes of the containing objects with the use of PathBuilder. When I append the code above with .and() and access the collection again via the pathBuilder variable, I naturally get the result equivalent to appending sql query with AND EXISTS..., which is not the desired result. I also tried to use getCollection().contains(), but I was unable to create the Expression<LanguageToName> that would describe such case.
Is there a way to create a Predicate that would filter entities by multiple attributes of the elements from a collection, that is a field of the queried entity?
I had similar issue and finally solved this with subquery (however, it seems to me that it works only for 1 level of nestedness).
My initial predicate was (it was making 2 independent sub-queries):
Predicate predicate = codeTable.customer.id.eq(customerId)
.and(codeTable.qualifierResults.any().customerQualifier.type.eq("TARGET_TYPE"))
.and(codeTable.qualifierResults.any().customerQualifier.referenceType.code.eq("TARGET_CODE"));
But the correct predicate that I ended up with was:
BooleanExpression customerQualifierCondition = JPAExpressions
.selectFrom(codeTableQualifierResult)
.where(codeTableQualifierResult.in(codeTable.qualifierResults),
codeTableQualifierResult.customerQualifier.type.eq("TARGET_TYPE"),
codeTableQualifierResult.customerQualifier.referenceType.code.eq("TARGET_CODE"))
.exists();
Predicate predicate = codeTable.customer.id.eq(customerId).and(customerQualifierCondition);
The idea is to write 1 separate sub-query where you apply all necessary conditions at once (instead of applying them for your collection independently).
I ran across the same problem in my project.
My workaround is to build the exists subquery manually.
Assuming that your both classes are mapped as Entities:
#Entity
#Table(name = "Offer")
public class Offer {
#Id
String id;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "offer")
List<LanguageToName> names;
}
#Entity
#Table(schema = "dcsdba", name = "Language_To_Name")
public class LanguageToName {
#Id
String id;
#ManyToOne(fetch= FetchType.LAZY)
#JoinColumn(name="Offer_id")
private Offer offer;
String name;
String language;
}
A simple query with any():
BooleanExpression namesFilter = QOffer.offer.names.any().name.eq("Esperanto");
maps to
select
offer0_.id as id1_7_
from
offer offer0_
where
exists (
select
1
from
dcsdba.language_to_name names1_
where
offer0_.id=names1_.offer_id
and names1_.name=?
)
A subquery:
BooleanExpression namesFilter = JPAExpressions.selectOne()
.from(languageToName)
.where(languageToName.offer.eq(QOffer.offer)
.and(languageToName.name.eq("Esperanto")))
.exists();
Maps to:
select
offer0_.id as id1_7_
from
offer offer0_
where
exists (
select
1
from
dcsdba.language_to_name languageto1_
where
languageto1_.offer_id=offer0_.id
and languageto1_.name=?
)
which matches perfectly previous SQL.
You can add additional conditions like:
BooleanExpression namesFilter = JPAExpressions.selectOne()
.from(languageToName)
.where(languageToName.offer.eq(QOffer.offer)
.and(languageToName.name.eq("Esperanto"))
.and(languageToName.language.like("E%")))
.exists();
I have a simple entity with one to many relationship
#Entity // and other # stuff
public class Member {
#Id
private Long id;
private String name;
private List<Program> programs;
...
}
#Entity
public class Program {
#Id
private Long id;
private Long programName;
private ProgramType programType;
private Long programCost;
...
}
Now using QueryDSL, I would like to query
'All members enrolled in a program with programType = "FULLTIME" and programCost > $1000'
I used the following predicate
Predicate predicate = QMember.member.programs.any()
.programType.eq(ProgramType.FULLTIME)
.and(QMember.member.programs.any().programCost.gt(1000));
with JPARepository
memberRepository.findAll(predicate);
Now the problem is that the two queries are independent. It returns al members with at least one program of type 'FULLTIME' or at least one program of cost greater than 1000.
Desired result : Return members if he has at least one program that is of type FULLTIME and cost > 1000.
Got some help here : https://groups.google.com/forum/#!topic/querydsl/hxdejLyqXos
Basically the conditions on the program need to be in a separate subQuery (a JPASubquery instance)
QProgram program = QProgram.program
JPASubQuery subQuery = new JPASubQuery();
subQuery.from(program)
.where(program.programType.eq(ProgramType.FULLTIME),
program.programCost.gt(1000));
Predicate predicate = QMember.member.name.eq("John")
.and(subQuery.exists());
memberRepository.findAll(predicate);
As mentionned by #Shahbour, this is not working anymore with QueryDsl 4.x+.
I had a similar case (except that my entities are bidirectionnal), and I've solved it with this :
QProgram program = QProgram.program;
QProgram member = QProgram.member;
Predicate predicate = JPAExpressions
.selectOne()
.from(program)
.where(program.member.id.eq(member.id),
program.programCost.gt(1000),
program.programType.eq(ProgramType.FULLTIME))
)
.exists();
memberRepository.findAll(predicate);
I want to create a HQL Query that can access Attributes of a Set of spezified Objects, let me explain via a short example:
Class Organization
public class Organization ...{
private int orgid;
private Set<DomainValue> languages = new HashSet<language>(0);
private Set<Address> adresses = new HashSet<Address>(0);
...
}
Class Address
public class Address implements java.io.Serializable {
private int addressId;
private String city;
private String postalCode;
private String streetName;
private String houseNumber;
...
}
Language
public class Orgunitlanguage implements java.io.Serializable {
private int orgLanguageId;
private Orgunit orgunit;
private Integer languageCd;
...
}
These examples are code snippets of working hibernate POJOs. So i have an organization that can have multiple addresses and languages.
I want the user to specify the search criteria, but limit them to one of each kind, so only one language, one postalcode etc.
lets say the user wants english organizations with a housenumber 22
so i would build a hql query like this:
"from organization o where o.languages.languageCd = 1 AND o.addresses.housenumber = 22"
Well and that dosen't work (illegal syntax) how do i access these Sets in the right way? Keep in mind i want to access a specific attribute and not just the whole object (which is really easy).
I can't seem to find a documentation that i understand so a little explaination would be nice.
Proper way to query on collections would be like this
from Organization o join o.languages l join o.addresses a where l.languageCd = 1 AND a.housenumber = 22
However, this query will return any organization that has at least one language with languageCd = 1 and at least one address with housenumber = 22. It will not filter out the languages and addresses that don't fit the criteria. Check this answer for a little more explanation on this.
I have Hibernate generated classes that contain other classes -
public class BookLoans implements java.io.Serializable {
private BookLoansId id;
private Borrower borrower;
private LibraryBranch libraryBranch;
private Book book;
private Date dateOut;
private Date dueDate;
}
where BookLoansId is -
public class BookLoansId implements java.io.Serializable {
private int bookId;
private int branchId;
private int cardNo;
}
which are primary keys in the tables Book, LibraryBranch and Borrower respectively. When I run this query -
sessionFactory.getCurrentSession().createSQLQuery(
"select * from library.tbl_book_loans l where cardNo = 4");
Hibernate returns a list of Object[] elements. If I try to iterate through this list, I get null objects. I've tried a couple of different methods from here and here.
Is there any way to find out how the objects are arranged within each Object[]?
To directly map the query result to an entity objct use addEntity(BookLoans.class);
sessionFactory.getCurrentSession().createSQLQuery(
"select * from library.tbl_book_loans l where cardNo = 4")
.addEntity(BookLoans.class);
See the docs(16.1.2. Entity queries):
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html
However the result of nulls you get from your attempt is strange. Hibernate should give you List of Objects arrays where each Object array represents the fields in one row of the result set. Check if the query actualy returns something.
I solved this by using HQL:
from library.tbl_book_loans where borrower.cardNo = 4
Hibernate now correctly populates all mapped entities.