Spring Web flux Mongo query - spring

Hi I am new to Spring web flux and facing the issue regarding Mongo reactive query.
I have following structure of my model class
public class Users implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private String id;
private String firstName;
private String middleName;
private String lastName;
private List<Email>emails;
}
public class Email implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String address;
boolean verified;
}
Now I have to query that if given email exists or not in the mong document as email filed is list of email as given above.
Can any one please me on this?
I have written the following query on repository
#Query(value = "{'emails.address' : ?0 }")
Mono<Users> findByEmails(String address);

try using
#Query("{'users.emails.address': ?0}")
Mono <Users> findUserByEmailAddress(final String address)

Related

Spring Data Rest - Save parent entity with children

I am new in Spring Data Rest. I want to save a parent entity with his children. The class are Distribution and FileIdVersion.
This is the Distribution entity.
#Entity
#DistributionValidator
public class Distribution extends AbstractAuditableJpaEntityImpl {
private static final long serialVersionUID = 1L;
#NotNull
#Length(min = 1, max = 256)
#SafeHtml
private String company;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "distribution")
#Size(max = 256)
private List<FileIdVersion> fileIdVersions = new ArrayList<>();
public Distribution() {
super();
}
public Distribution(final String company, final String name, final String topic, final ZonedDateTime uploadDate,
final ZonedDateTime setupDate, final UUID uuid, final List<FileIdVersion> fileIdVersions,
final List<Bundle> bundles, final List<String> recipientId) {
super();
this.company = company;
this.fileIdVersions = fileIdVersions;
}
}
This is the FileIdVersion entity.
#Entity(name = "bundle_file_id_version")
public class FileIdVersion extends AbstractJpaEntityImpl implements Serializable {
private static final long serialVersionUID = 1L;
#NotNull
#FileId
private String fileId;
#FileVersion
private String fileVersion;
#ManyToOne
#NotNull
#JsonIgnore
private Bundle bundle;
public FileIdVersion() {}
}
I want to save one distribution object with his fileIdVersion. I am trying something like this:
This request only persist in BBDD one record of distribution, but not persist any records in FileIdVersion entity. How I can to persist the distribution with his file id versions? Thank you in advance!!!

JPQL Join and class cast exception

I am using JPA with Hibernate in spring boot.
I have two jpa entities
#Entity
#Table(name="courses_type")
public class CoursesType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="course_id")
private int courseId;
#Column(name="level")
private int level;
private int credential;
private String status;
private String type;
#Column(name="updated_by")
private int updatedBy;
#Column(name="updated_on")
private Timestamp updatedOn;
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(name="credential", referencedColumnName="value_id",insertable=false,updatable=false)
#Where(clause="status='live'")
private BaseAttributeList credentialData;
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(name="level", referencedColumnName="value_id",insertable=false,updatable=false)
#Where(clause="status='live'")
private BaseAttributeList courseLevelData;
... setters and getters
}
Second Entity
#Entity
#Table(name="attribute_list")
public class AttributeList implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="value_id")
private int valueId;
private String status;
#Column(name="value_name")
private String valueName;
}
Now I am trying to write a JPQL Query in CourseTypeRepo
#Query("Select sct.courseId, sct.credential, sct.credentialData from CoursesType"
+ " sct where sct.courseId IN(?1) and sct.status = ?2")
List<CoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);
Now when I am iterating the result, I am getting class Cast Exception that
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.domain.CoursesType
Basically what I am trying to fetch the complete data using one jpql query.
How should I fix this?
If don't want to fetch full object but only some its properties you have to provide a projection then use it in your query method, for example:
public interface PartialCoursesType {
Integer getCourseId(),
Integer getCredential(),
BaseAttributeList getCredentialData()
}
#Query("select sct.courseId as courseId, sct.credential as credential, sct.credentialData as credentialData...")
List<PartialCoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);
To make the trick works you have to use aliases in the query...

Spring Roo: Showing and downloading a document

I added a document entity to my application. Applicant entity has a One-to-Many relation with document, i.e. an applicant can upload many documents. I'm still not able to show this document in my app. I want to be able to show the document and download it when the user clicks on the document's link.
I tried to implement the code here but the result was a window with a 404 error (description The requested resource is not available).
I'm using MySQL as database.
Here is the rest of my code
Applicant.java
#RooJavaBean
#RooToString
#RooJpaActiveRecord
public class Applicant {
/**
*/
#NotNull
private String name;
/**
*/
#NotNull
private String phone;
/**
*/
private String address;
/**
*/
#NotNull
private String nationality;
/**
*/
#NotNull
private String email;
/**
*/
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(style = "M-")
private Date dateOfBirth;
/**
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "applicant")
private Set<Document> files = new HashSet<Document>();
}
Document.java
#RooJavaBean
#RooToString
#RooJpaActiveRecord
public class Document {
private static final Log log = LogFactory.getLog(Document.class);
#NotNull
#Lob
#Basic(fetch = FetchType.LAZY)
private byte[] content;
#Transient
#Size(max = 100)
private String url;
private String filename;
private Long size;
#NotNull
#Size(max = 30)
private String name;
#NotNull
#Size(max = 500)
private String description;
private String contentType;
/**
*/
#ManyToOne
#JoinColumn(name = "applicant_id")
private Applicant applicant;
}
I had a similar challenge some weeks ago. I just generated an application with another code generator (generjee). It generates well working One-To-Many document upload/download, if you select the "Enable upload file attachments" checkbox of an entity. Then I copied the document upload/download/show code from it into my spring roo project. Worked fine.
Don't forget to define commons-fileupload in the pom.xml and if you use PrimeFaces, you must set the PrimeFaces FileUpload Filter in web.xml. It's all in the generjee produces code. Just copy&paste.

want to autowire DAO class in my entity class

i have a method which i need to call in my entity class company.java.
but when i run my application it throws null pointer exception didn't fount that DAO object in entity class..
How can i get that object in entity class please help
This is my entity class..
package com.salebuild.model;
/**
* Define a company.
*
* #author mseritan
*/
#Entity
#Table(name = "company", uniqueConstraints = {#UniqueConstraint(columnNames = "name")})
#XmlRootElement
#XmlSeeAlso(value = ArrayList.class)
public class Company implements PublishableIF, Serializable, PersistableIF, HistoryIF, AddressableIF {
private static final Logger log = LoggerFactory.getLogger( Company.class );
#Autowired
private CompanyDAO companyDAO;
// CONSTANTS -----------------------------------------------------------------------------------
private static final long serialVersionUID = 1L;
// ATTRIBUTES ----------------------------------------------------------------------------------
private Long id;
#NotBlank
private String name;
private String formerName;
private CorporateTitle topLevelExec;
private List<CompanySite> sites;
private List<CompanyAlias> aliases;
#NotNull
private Industry industry;
private Company parentCompany;
private String emailTopology;
#NotNull
private Double revenue;
#NotNull
private Long numberEmployees;
private CustomerType.Type customerType;
private Boolean recruiter = false;
private int publishState;
private CompanyStatus status;
private Boolean excludeCompany = false;
private CompanyType companyType;
private String salesifyCompanyId;
private CompanySiteType companySiteType;
private String websiteUrl;
private String sourceVendor;
private String notes;
private List<CompanySpecializedRanking> specializedList = new ArrayList<CompanySpecializedRanking>();
#NotNull
private NAICSCode naicsCode;
#NotNull
private SICCode sicCode;
private Long version;
private List<Technology> technologies = new ArrayList<Technology>();
private List<CompanyContact> contacts;
private String phoneNumber;
private String faxNumber;
private String email;
private User userCreated;
private Date dateCreated;
private User userLastModified;
private Date dateLastModified;
private User userLastResearcher;
private Date dateLastResearcher;
#NotBlank
private String street1;
private String street2;
private String street3;
private String city;
private String zipCode;
private State state;
private Country country;
private String specRankingListName;
private Integer specRankingRank;
private Integer specRankingYear;
private String modifiedCompanyName;
private String formattedRevenue;
private String formattedEmployeeSize;
private List<JobPostingRaw> unconfirmedTechnologies;
// ACESSORS ------------------------------------------------------------------------------------
//getter setter for other fields //
this.specRankingYear = specRankingYear;
}
/**
* #param modifiedCompanyName
*
*/
#Column(name="modifiedCompanyName")
public String getModifiedCompanyName() {
return modifiedCompanyName;
}
public void setModifiedCompanyName(String modifiedCompanyName) {
if(modifiedCompanyName==null)
this.modifiedCompanyName=modifiedCompanyName;
else{
this.modifiedCompanyName =companyDAO.updateCompanyName(modifiedCompanyName);
}
}
#Transient
public List<JobPostingRaw> getUnconfirmedTechnologies() {
return unconfirmedTechnologies;
}
public void setUnconfirmedTechnologies(
List<JobPostingRaw> unconfirmedTechnologies) {
this.unconfirmedTechnologies = unconfirmedTechnologies;
}
}
my DAO class is like that --
package com.salebuild.dao;
import com.salebuild.model.Company;
import com.salebuild.model.search.EntitySearchCriteria;
import com.salebuild.model.search.SortedResultsPage;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public interface CompanyDAO extends CrudDAO<Company> {
Company findByNameOrAlias(String name);
List<Company> findBySearchTerm(String searchTerm, Integer start, Integer count);
// SortedResultsPage<Company> findPaged(EntitySearchCriteria criteria);
List<Long> findIds(EntitySearchCriteria criteria);
List<Company> find(Collection<Long> ids);
/**
* For just finding the company name and not looking for alias names.
*
* #param name
* #return
*/
public Company findByName( String name );
public Company findByModifiedName(String name,Company... c);
public int companyCountSinceLastLogin(Long id);
Set<Long> findDistinctIds(EntitySearchCriteria criteria);
public Integer getCompanyCountByRegion(Long regionId,List techCatIds);
List<Company> findAllCompanies(Company instance);
public List<Company> findAllModifiedCompanies(Company instance);
public String updateCompanyName(String name);
}
The easiest option is to implement factory for building entities. Then you can use AutowireCapableBeanFactory to autowire dependencies:
public abstract class GenericFactory<T> {
#Autowired
private AutowireCapableBeanFactory autowireBeanFactory;
public T createBean() {
// creation logic
autowireBeanFactory.autowireBean(createdBean);
return createdBean;
}
}
Of course you can pass object (created or retrieved) and just autowire it.
Another option is to use #Configurable - it automatically injects dependencies. http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-atconfigurable
You can find more details in my post: http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html
JPA entities are meant to be POJOs i.e. simple Java beans which do not have dependencies and have getters and setters which contain no complex logic.
It would be better to create a service which is responsible for saving and updating your entity which is used throughout your code. This service can then be responsible for executing the logic you wish to put in your setter using dependencies which can be autowired.
The issue you have is that you Spring is not responsible for the creation of your entity. You either instantiate it using new or you obtain it from your JPA implementation. Either way there is no opportunity for Spring to autowire declared dependencies.
As an aside it's not good practice to autowire private variables. See this blog post for a fuller discussion.

How to add properties to the relationship in Spring data neo4j when we use createRelationshipBetween

For example I want to make relationship between User A and User B and they have RelationshipEntity named MakeFriend, I am used code below, but I am also want to set in relation entity some property values like role = 10.........
userRepository.createRelationshipBetween(startUser, endUser, MakeFriend.class, RelTypes.FRIEND.name());
#RelationshipEntity
public class MakeFriend {
#GraphId
private Long id;
private String role;
#StartNode
private UserEntity startUser;
#EndNode
private UserEntity endUser
#NodeEntity
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
public static final String FRIEND = "FRIEND";
public static final String JOYNED = "JOYNED";
#GraphId
private Long id;
#Indexed(unique = true)
private Long userId;
private String email;
You could could add the following to your UserEntity class:
#RelatedToVia(type = RelTypes.FRIEND, direction = Direction.BOTH)
private MakeFriend friend;
friend.setRole("yourRole");
Another way to do it, when you're using the advanced mapping mode, is using one of the NodeBacked.relateTo() methods. Then add the property to the returned Relationship.
And a third way, it to use the Neo4jTemplate.createRelationshipBetween() method and provide your properties (e.g. role) as the final argument.

Resources