Spring Data query over two documents - spring

I have an m:n connection in my MongoDB, MessageUserConnection is the class between User and Message.
Now I will get all MessageUserConnections where MessageUserConnection#confirmationNeeded is true, read is false and Message#receiveDate is not older than the last week.
Is there any possibility to do this with Spring Data?
Thanks a lot!
public class MessageUserConnection {
#Id
private String id;
#DBRef
private User userCreatedMessage;
#DBRef
private Message message;
private Boolean confirmationNeeded;
private Boolean read;
}
public class Message {
#Id
private String id;
private String title;
private String message;
private DateTime receiveDate;
}
[EDIT]
I have tried it by my own:
#Query("FROM MessageUserConnection AS muc WHERE muc.confirmationNeeded = ?0 AND muc.message.receiveDate = ?1")
List<MessageUserConnection> findMessageUserConnectionByConfirmationNeededAndReceiveDate(final Boolean confirmationNeeded, final DateTime receiveDate);
and I get the following exception:
Caused by: com.mongodb.util.JSONParseException:
FROM MessageUserConnection AS muc WHERE muc.confirmationNeeded = "_param_0" AND muc.message.receiveDate = "_param_1"
Does anyone know what I am doing wrong here?
Thanks a lot!
[EDIT]
I run into another problem. My query currently looks like this.
#Query("{$and : [{'confirmationNeeded' : ?0}, {'message.receiveDate' : ?1}]}")
where confirmationNeeded is a boolean and message.receiveDate is Joda#DateTime. With this query I get the following exception:
org.springframework.data.mapping.model.MappingException: Invalid path reference message.receiveDate! Associations can only be pointed to directly or via their id property!
Does that mean that I only can join to message.id?
Thanks a lot!

Related

Spring Boot + Webflux + Reactive MongoDB - get document by property Id

I'd like to find all Offer documents by Offer.ProductProperties.brand:
#Document(collection = "offers")
public class Offer {
#Id
private String id;
#NotNull
#DBRef
private ProductProperties properties;
ProductProperties:
#Document(collection = "product_properties")
public class ProductProperties {
#Id
private String id;
#NotNull
#NotEmpty
private String brand;
Service:
Flux<ProductProperties> all = productPropertiesRepository.findAllByBrand(brand);
List<String> productPropIds = all.toStream()
.map(ProductProperties::getId)
.collect(Collectors.toList());
Flux<Offer> byProperties = offerRepository.findAllByProperties_Id(productPropIds);
But unfortunately byProperties is empty. Why?
My repository:
public interface OfferRepository extends ReactiveMongoRepository<Offer, String> {
Flux<Offer> findAllByProperties_Id(List<String> productPropertiesIds);
}
How to find all Offers by ProductProperties.brand?
Thanks!
After reading some documentation found out that You cannot query with #DBRef. Hence the message
Invalid path reference properties.brand! Associations can only be
pointed to directly or via their id property
If you remove DBRef from the field, you should be able to query by findAllByProperties_BrandAndProperties_Capacity.
So the only ways is how you are doing. i.e. Fetch id's and query by id.
As I said in the comment, the reason it is not working is because return type of findAllByProperties_Id is a Flux. So unless u execute a terminal operation, you wont have any result. Try
byProperties.collectList().block()

How can I include or exclude a record according to a boolean parameter using Spring Data JPA?

I am not so into Spring Data JPA and I have the following doubt about how to implement a simple query.
I have this AccomodationMedia entity class mapping the accomodation_media on my database:
#Entity
#Table(name = "accomodation_media")
public class AccomodationMedia {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "id_accomodation")
private Long idAccomodation;
#Column(name = "is_master")
private boolean isMaster;
#Lob
#Column(name = "media")
private byte[] media;
private String description;
private Date time_stamp;
public AccomodationMedia() {
}
...............................................................
...............................................................
...............................................................
// GETTER AND SETTER METHODS
...............................................................
...............................................................
...............................................................
}
The instance of this class represents the photo associated to an accomodation (an hotel)
So as you can see in the prvious code snippet I have this field :
#Column(name = "id_accomodation")
private Long idAccomodation;
that contains the id of an accomodation (the id of an hotel on my database).
I also have this boolean field that specify if an image is the master image or not:
#Column(name = "is_master")
private boolean isMaster;
So, at this time, in my repository class I have this method that should return all the images associated to a specific hotel:
#Repository
public interface AccomodationMediaDAO extends JpaRepository<AccomodationMedia, Long> {
List<AccomodationMedia> findByIdAccomodation(Long accomodationId);
}
I want to modify this method passing also the boolean parameter that specify if have to be returned also the master image or only the images that are not master.
So I tryied doing in this way:
List<AccomodationMedia> findByIdAccomodationAndIsMaster(Long accomodationId, boolean isMaster);
but this is not correct because setting to true the isMaster parameter it will return only the master image (because it is first selecting all the Accomodation having a specific accomodation ID and then the one that have the isMaster field setted as true).
So, how can I correctly create this query that use the isMaster boolean parameter to include or exclude the AccomodationMedia instance that represent my master image?
I know that I can use also native SQL or HQL to do it but I prefer do it using the "query creation from method names"
I don't have how to test this, but essentially your final query should be:
id_accomodation = ?1 AND (is_master = ?2 OR is_master = false)
So I would try the following method signature:
findByIdAccomodationAndIsMasterOrIsMasterFalse(Long accomodationId, boolean isMaster);
I would go with two methods one for isMaster true, while second for false value like this:
List<AccomodationMedia> findByIdAccomodationAndIsMasterFalse(Long accomodationId);
List<AccomodationMedia> findByIdAccomodationAndIsMasterTrue(Long accomodationId);
Change your acommodation id as accomodationId instead of idAccomodation. When you write findByIdAccomodationAndIsMaster spring confusing findByIdAccomodationAndIsMaster
Try this this convention
#Column(name = "accomodation_id")
private Long accomodationId;

Spring JPA mongodb using annotations

Help me understand this. I am using spring-data-mongodb without hibernate or any other jpa provider. My domain model is like this:
public class User {
#Id
private String id;
private String username;
private String password;
...
}
I run a test class to populate a few users in my mongodb, which works fine. But if I add a few more annotations like this:
public class User {
#Id
private String id;
#Field(value="uname") private String username;
#Field(value="pass")private String password;
...
}
my test class adds just one user, the next one throws exception complaining of duplicate entries -
org.springframework.dao.DuplicateKeyException: E11000 duplicate key error index: gldata.user.$username_-1 dup key: { : null }; nested exception is com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: gldata.user.$username_-1 dup key: { : null }
What am I missing here?
Although I didn't find out why this was happening, I found a workaround. Using ObjectId instead of String for id field, works very well.

Result row : null from HibernateTemplate Find()

The following line is returning nulls:
List accountList = hibernateTemplate.find("from Accounts a where a.userId=?",userId);
I am getting following information in the Console:
2013-04-03 21:09:48 DEBUG Loader:1197 - result row: null
2013-04-03 21:09:48 DEBUG Loader:1197 - result row: null
Here is my Entity class:
#Repository
#Entity
#Table(name = "ACCOUNTS")
public class Accounts {
#Column(name="ACCOUNT_ID")
#Id
#GeneratedValue
private int accountId;
#Column(name="ACCOUNT_NUMBER")
private String accountNumber;
#Column(name="ACCOUNT_TYPE_CODE")
private String accountTypeCode;
#Column(name="USER_ID")
private String userId;
#Column(name="ACCOUNT_NAME")
private String accountName;
#Column(name="DATE_OPENED")
private Date dateOpened;
#Column(name="DATE_CLOSED")
private Date dateClosed;
#Column(name="CURRENT_BALANCE")
private double currentBalance;
#Column(name="OTHER_ACCOUNT_DETAILS")
private String otherAccountDetails;
#Column(name="ADD_TS")
private Date addTimestamp;
#Column(name="ADD_USR")
private String addUser;
#Column(name="UPDT_TS")
private Date updateTimestamp;
#Column(name="UPDT_USR")
private String updateUser;
#ManyToOne
private Customer customer;
Can anyone please help me with this? I would really appreciate it.
Here is the query that Hibernate generated
Hibernate: select accounts0_.ACCOUNT_ID as ACCOUNT1_23_, accounts0_.ACCOUNT_NAME as ACCOUNT2_23_, accounts0_.ACCOUNT_NUMBER as ACCOUNT3_23_, accounts0_.ACCOUNT_TYPE_CODE as ACCOUNT4_23_, accounts0_.ADD_TS as ADD5_23_, accounts0_.ADD_USR as ADD6_23_, accounts0_.CURRENT_BALANCE as CURRENT7_23_, accounts0_.customer_CUSTOMER_ID as customer14_23_, accounts0_.DATE_CLOSED as DATE8_23_, accounts0_.DATE_OPENED as DATE9_23_, accounts0_.OTHER_ACCOUNT_DETAILS as OTHER10_23_, accounts0_.UPDT_TS as UPDT11_23_, accounts0_.UPDT_USR as UPDT12_23_, accounts0_.USER_ID as USER13_23_ from ACCOUNTS accounts0_ where accounts0_.USER_ID=?
is there something wrong in query? or domain configuration?
Please help me.
I'm a little don't understand that why set the column of USER_ID String(varchar) type, but about your situation, you can write like this:
hibernateTemplate.find("from Accounts a where a.userId='" + userId + "'");
it'll work well, maybe help you:)

Hibernate tuple criteria queries

I am trying to create a query using hibernate following the example given in section 9.2 of chapter 9
The difference with my attempt is I am using spring MVC 3.0. Here is my Address class along with the method i created.
#RooJavaBean
#RooToString
#RooEntity
#RooJson
public class Address {
#NotNull
#Size(min = 1)
private String street1;
#Size(max = 100)
private String street2;
private String postalcode;
private String zipcode;
#NotNull
#ManyToOne
private City city;
#NotNull
#ManyToOne
private Country country;
#ManyToOne
private AddressType addressType;
#Transient
public static List<Tuple> jqgridAddresses(Long pID){
CriteriaBuilder builder = Address.entityManager().getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<Address> addressRoot = criteria.from( Address.class );
criteria.multiselect(addressRoot.get("id"), addressRoot.get("street1"), addressRoot.get("street2"));
criteria.where(builder.equal(addressRoot.<Set<Long>>get("id"), pID));
return Address.entityManager().createQuery( criteria ).getResultList();
}
}
The method called jqgridAddresses above is the focus. I opted not to use the "Path" because when I say something like Path idPath = addressRoot.get( Address_.id ); as in section 9.2 of the documentation, the PathAddress_.id stuff produces a compilation error.
The method above returns an empty list of type Tuple as its size is zero even when it should contain something. This suggests that the query failed. Can someone please advise me.
OK so i made some minor adjustments to my logic which is specific to my project, however, the following approach worked perfectly. Hope it hepls someone in need !
#Transient
public static List<Tuple> jqgridPersons(Boolean isStudent, String column, String orderType, int limitStart, int limitAmount){
CriteriaBuilder builder = Person.entityManager().getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<Person> personRoot = criteria.from(Person.class );
criteria.select(builder.tuple(personRoot.get("id"), personRoot.get("firstName"), personRoot.get("lastName"), personRoot.get("dateOfBirth"), personRoot.get("gender"), personRoot.get("maritalStatus")));
criteria.where(builder.equal( personRoot.get("isStudent"), true));
if(orderType.equals("desc")){
criteria.orderBy(builder.desc(personRoot.get(column)));
}else{
criteria.orderBy(builder.asc(personRoot.get(column)));
}
return Address.entityManager().createQuery( criteria ).setFirstResult(limitStart).setMaxResults(limitAmount).getResultList();
}

Resources