Spring Roo: Showing and downloading a document - spring

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.

Related

Auto populate created_date, last_modified_date, created_by and last_modified_by in entity : Hibernate with JPA

I am new to Hibernate and JPA. I have several entities, each of which contains following four columns:
1. created_by
2. last_modified_by
3. created_date
4. last_modified_date
I would like these columns to get auto-populated while saving the associated entity.
Two sample entities are as follows:
Entity 1:
#Entity
#Table(name = "my_entity1")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity1 implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_by")
private String lastModifiedBy;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private String lastModifiedDate;
}
Entity 2:
#Entity
#Table(name = "my_entity2")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity2 implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "description")
private String description;
#Column(name = "created_by")
private String createdBy;
#Column(name = "last_modified_by")
private String lastModifiedBy;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private String lastModifiedDate;
}
In this context, I have gone through following posts: How to autogenerate created or modified timestamp field?, How can you make a created_at column generate the creation date-time automatically like an ID automatically gets created?.
I am getting how to capture the dates fields but I cannot understand how to capture created_by and last_modified_by.
Auditing Author using AuditorAware and Spring Security...
To tell JPA about currently logged in user we will need to provide an
implementation of AuditorAware and override getCurrentAuditor()
method. And inside getCurrentAuditor() we will need to fetch currently
logged in user.
Like this:
public class AuditorAwareImpl implements AuditorAware<String> {
#Override
public String getCurrentAuditor() {
return "TestUser";
// Can use Spring Security to return currently logged in user
// return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
}
}
Now enable jpa auditing by using #EnableJpaAuditing
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
#Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
Look at this to get more details....

Spring Web flux Mongo query

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)

Model mapper not mapping values

I am mapping a collection with a collection.Its getting mapped successfully most of time but sometime its getting failed and i am getting null values.
ArrayList<RiskRequestDTO> riskList = new ArrayList<>();
Iterable<Risk> risks = RiskRepository.findAll();
if (risks != null) {
java.lang.reflect.Type targetListType = new TypeToken<List<riskRequestDTO>>() {
}.getType();
riskList = modelMapper.map(risks, targetListType);
}
Risk DTO
i am facing some issue to add complete code so i removed setters and getters.I am confirming that the relevant annotations are present with setters and getters
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"riskId", "localeTranslations", "lastModifiedAt", "lastModifiedBy"
})
public class RiskRequestDTO {
#JsonProperty("riskId")
private int riskId;
#JsonProperty("localeTranslations")
private Set<LocaleTranslation> localeTranslations;
#JsonProperty("lastModifiedAt")
private Date lastModifiedAt;
#JsonProperty("lastModifiedBy")
private UserViewDTO lastModifiedBy;
Risk Model
I am facing some issue to add complete code so i removed setters and getters of these entity
#Entity
#Table(name = "risk")
public class Risk {
/**
* risk_id , primary key.
*/
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = “risk_id")
private int riskId;
/**
* last modified date.
*/
#Column(name = "last_modified_at")
private Date lastModifiedAt;
/**
* details of locale.
*/
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name="risk_to_local_translation", joinColumns={ #JoinColumn(name="risk_id") }, inverseJoinColumns={ #JoinColumn(name="locale_translation_id") })
private Set<LocaleTranslation> localeTranslations;
/**
* details of the user who updated the recommendations.
*/
#ManyToOne( fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "last_modified_by", nullable = false)
private User lastModifiedBy;
I have updated question with DTO and Entity model

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!!!

How to make one Model for similar tables?

I have several similar tables in DB.
Now I use for each table own Model and Repository
But I think, this is not right decision.
Can I make a one Model and Repository for all similar tables?
#Entity
#Table(name = "BEDROOM", schema = "public")
public class BedroomModel extends AllFinishProductModel{
#Column(name = "PHOTO")
private String photo;
#Id
#Column(name = "ID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column
private String name;
#Column(name = "DESCRIPTION")
private String description;
#Column(name = "STRUCTURE") //organza, curtain ....
private String structure;
#Column(name = "PAINT") //abstraction, geometric ....
private String paint;
#Column(name = "HEIGHT")
private String height;
#Column(name = "COLOR")
private String color;
#Column(name = "QUANTITY")
private Double quantity;
#Column(name = "PRICE")
private BigDecimal price;
#Column(name = "SEWED")
private String itIsSewed;
... getters and setters
}
I have a similar tables: CABINET, GUESTROOM, CHILDREN_ROOM, KITCHEN, CURTAIN and TULLE.
Which code should be used for repository?
I tried to find answers to the questions inhttps://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html
But I don't find answers here.
Can you give advice, how to make it or link?
You can use entity inheritance with #MappedSuperclass annotation on parent class to get common properties in child classes/tables.
So, for example you have a parent Room entity with common properties, which you annotate with #MappedSuperclass.
#MappedSuperclass
public class Room {
#Column
private String name;
#Column(name = "DESCRIPTION")
private String description;
// some more common properties
}
And concrete rooms, e.g.:
#Entity
public class Bedroom extends Room
{
// common properties will be inherited
private Bed bed;
private NightLamp nightLamp;
}
Now, the important part is that Room is not mapped as any table. The room is a "virtual" table, which doesn't exist in the db. Only concrete entities exist as tables, like Bedroom.
Here you have the link to the official javadoc:
http://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html

Resources