#RequestMapping(method=RequestMethod.POST, value= {"/LMSServer/getNoOfDaysOfApplicationBycellNo"} )
#PreAuthorize("hasAuthority('CUSTOMER_MANAGEMENT_R') OR hasAuthority('CUSTOMER_MANAGEMENT_RW')")
public BasicResponce getNoOfDaysOfApplicationBycellNo(#RequestParam(value = "cellNo") long cellNo)
{
if(LOG.isInfoEnabled()){
LOG.info("WebClientRestContoller.getNoOfDaysOfApplicationBycellNo--Start");
LOG.info("Cell NO: "+cellNo);
}
BasicResponce authResp = null;
try {
Customer fromDB= (Customer) objLMSDAO.getDetailsByCellno(cellNo);
DaysOfApplicationResponseDTO toSend= new DaysOfApplicationResponseDTO();
toSend.setCreatedAt(fromDB.getCreatedAt()+"");
toSend.setUpdatedAt(fromDB.getUpdatedAt()+"");
toSend.setRequested_Action(true);
authResp=toSend;
} catch (Exception e) {
e.printStackTrace();
}
if(LOG.isInfoEnabled()){
LOG.info("Returned Response is:");
LOG.info("Response Requested_Action: {} ",new Object[]{authResp.getRequested_Action()});
LOG.info("WebClientRestContoller.getNoOfDaysOfApplicationBycellNo--End");
}
return authResp;
}
The above is my main code. I want to print the difference of days (no. of days between createdAt and updatedAt). Where do I write this logic? I remember in java we use System.out.println to display output, but here I don't know to display code on Postman.
Below is my DTO:
public class DaysOfApplicationResponseDTO extends BasicResponce{
private String createdAt;
private String updatedAt;
private String days;
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
private List<CustomerLoanSummaryResponseDTO> LoanApplicationDummyResponseList;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public List<CustomerLoanSummaryResponseDTO> getLoanApplicationDummyResponseList() {
return LoanApplicationDummyResponseList;
}
public void setLoanApplicationDummyResponseList(
List<CustomerLoanSummaryResponseDTO> loanApplicationDummyResponseList) {
LoanApplicationDummyResponseList = loanApplicationDummyResponseList;
}
public DaysOfApplicationResponseDTO() {
super();
}
public DaysOfApplicationResponseDTO(String createdAt, String UpdatedAt, String days,
List<CustomerLoanSummaryResponseDTO> loanApplicationDummyResponseList) {
super();
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.days = days;
this.LoanApplicationDummyResponseList = loanApplicationDummyResponseList;
}
}
You can introduce service classes (#service annotation) to your project for domain logic. You have to break down and organize the project into a suitable project structure (so that your controllers, entities, services are in different packages for clarity). Better read on those for more information.
Here is a helpful stack-overflow question,
What is the recommended project structure for spring boot rest projects?
Related
I am trying to use the annotation based approach to audit my elasticsearch document using spring-data-elasticsearch. I followed the JPA guide while implementing my classes/setup.
My code looks like this:
#Configuration
#EnableJpaAuditing
public class SpringSecurityAuditorAwareConfiguration {
#Bean
public AuditorAware<String> auditorProvider() {
return new SpringSecurityAuditorAware();
}
}
public class SpringSecurityAuditorAware implements AuditorAware<String> {
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.filter(Authentication::isAuthenticated)
.map(Authentication::getPrincipal)
.map(User.class::cast)
.map(User::getUsername);
}
}
#Document(indexName = "myEntity", type = "myEntityType")
public class MyEntity {
#Id
private String id;
#CreatedBy
protected String createdBy;
#CreatedDate
protected OffsetDateTime createdDate;
#LastModifiedBy
protected String lastModifiedBy;
#LastModifiedDate
protected OffsetDateTime lastModifiedDate;
public void setDictionaryId(DictionaryId dictionaryId) {
this.dictionaryId = dictionaryId;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public OffsetDateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(OffsetDateTime createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public OffsetDateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(OffsetDateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
Unfortunately it when I save a new instance the properties are always set to null. Does spring-data-elasticsearch support the annotation based approach?
Edit:
This is implemented since version 4.0 which has been released in May 2020.
Original answer:
No, this is currently not supported in Spring Data Elasticsearch.
Please create a ticket to add support for this, this is definitely a feature worth to have.
I'm fairly new to Java and am working on a Spring Boot database application (MySQL) in which I am trying to create a method which will allow for a Client (Java object) to be deleted from my database using a Dao/CrudRepository and searching by the unique Id. I am receiving an error when running stating "error: incompatible types: int cannot be converted to Client"
I've compared to a similar program created in which I used the same syntax with no issue, so unsure why I am getting this error when processing.
My object is set up like so:
#Entity
public class Client {
#Id
#GeneratedValue
private int id;
#NotNull
#Size(min=1, message = "Must enter client name")
private String name;
#NotNull
#Size(min=1, message= "Must enter contact's name")
private String contact;
#NotNull
#Size(min=1, message="Must enter primary office location")
private String location;
#NotNull(message="Must enter contract start date")
private String startDate;
#NotNull(message="Must enter contract end date")
private String endDate;
#NotNull(message="Must enter employee count")
private Integer employeeCount;
private PhilanthropyInterest interest;
public Client(String name, String contact, String location, String startDate, String endDate, Integer employeeCount) {
this.name = name;
this.contact = contact;
this.location = location;
this.startDate = startDate;
this.endDate = endDate;
this.employeeCount = employeeCount;
}
public Client () { }
public int getId() { return id; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public Integer getEmployeeCount() {
return employeeCount;
}
public void setEmployeeCount(Integer employeeCount) {
this.employeeCount = employeeCount;
}
public PhilanthropyInterest getInterest() { return interest; }
public void setInterest(PhilanthropyInterest interest) { this.interest = interest; }
And my controller method in which I am receiving the error is:
#RequestMapping(value = "remove", method = RequestMethod.GET)
public String displayRemoveAddClientForm(Model model) {
model.addAttribute("clients", clientDao.findAll());
model.addAttribute("title", "Remove Client");
return "clients/remove";
}
#RequestMapping(value = "remove", method = RequestMethod.POST)
public String processRemoveClientForm(#RequestParam int[] clientIds) {
for (int clientId : clientIds) {
clientDao.delete(clientId);
}
return "redirect:";
}
And my ClientDao class is:
#Repository
#Transactional
public interface ClientDao extends CrudRepository<Client, Integer> {
}
The error showing in IntelliJ states:
delete
(org.launchcode.spcdb.models.Client)
in CrudRepository cannot be applied
to
(int)
and when running, I am receiving:
error: incompatible types: int cannot be converted to Client
clientDao.delete(clientId);
here you can find the documentation for CRUDRepository : https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html
You will see that the method delete(T entity) method take an Object as argument.
In your case, it is a Client.
As you are using
public interface ClientDao extends CrudRepository<Client, Integer>
the method delete(T entity) that you use is expecting an Client.
So try :
public String processRemoveClientForm(#RequestParam int[] clientIds) {
List<Client> clientList = clientDAO.findByIds(clientIds);
for (Client client : clientList) {
clientDao.delete(client );
}
}
this should work. Nerver forget that you are manipulating Object in this case.
I am using spring boot, therefore I am not using any xml files for configurations.
What I have to do is to EnableMongoAuditing for saving createdDate, lastModifiedDate etc while saving data using MongoRepositories.
My model class
#Component
#Document(collection = "CAPPING")
public class TemporaryCapping extends BaseEntity {
#Field("contract_id")
private BigInteger contractId;
#Field("period_id")
private BigInteger periodId;
#Field("user_id")
private BigInteger userId;
#Field("amount")
private Double amount;
#Field("type_of_capping")
private TypeOfCapping typeOfCapping;
public BigInteger getContractId() {
return contractId;
}
public void setContractId(BigInteger contractId) {
this.contractId = contractId;
}
public BigInteger getPeriodId() {
return periodId;
}
public void setPeriodId(BigInteger periodId) {
this.periodId = periodId;
}
public BigInteger getUserId() {
return userId;
}
public void setUserId(BigInteger userId) {
this.userId = userId;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public TypeOfCapping getTypeOfCapping() {
return typeOfCapping;
}
public void setTypeOfCapping(TypeOfCapping typeOfCapping) {
this.typeOfCapping = typeOfCapping;
}
}
public class BaseEntity implements Serializable{
#Id
#Indexed(unique = true)
private BigInteger id;
#CreatedDate
private DateTime createdDate;
#Field("modified_date")
private BigInteger modifiedDate;
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
public BigInteger getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(BigInteger modifiedDate) {
this.modifiedDate = modifiedDate;
}
I have used #CreateDate annotation for saving createDate.
and I have used jodatime dependency for DateTime
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.7</version>
</dependency>
spring-data-mongodb is also added in the dependencies.
This is my main application class
#SpringBootApplication
#EnableMongoAuditing
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Where I am wrong in this impelmentation as the date is not getting saved in database?
Also I know that for saving #createdBy you need to write AuditorAware bean but for now I am just trying to save createdBy.
Where should #EnableMongoAuditing be used?
In my application I configure through Java code. I use #EnableMongAuditing this way and also create convertes for ZonedDateTime.
#Configuration
#EnableMongoAuditing
#EnableMongoRepositories(basePackages = { BASE_PACKAGE })
public class MongoConfiguration extends AbstractMongoConfiguration {
public static final String BASE_PACKAGE = "package.with.aggregates";
#Value("${spring.data.mongodb.uri}")
private String mongoUri;
#Value("${spring.data.mongodb.database}")
private String databaseName;
#Override
protected String getDatabaseName() {
return databaseName;
}
#Override
public Mongo mongo() throws Exception {
return new MongoClient(new MongoClientURI(mongoUri));
}
// Here you must add converters to Joda datetypes. In my solution is ZonedDateTime
#Override
public CustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<>();
converterList.add(new DateToZonedDateTimeConverter());
converterList.add(new ZonedDateTimeToDateConverter());
return new CustomConversions(converterList);
}
#Override
protected String getMappingBasePackage() {
return BASE_PACKAGE;
}
}
#EnableMongoAuditing can actually be placed anywhere in configurations (next to #Configuration annotation)
I have a very simple bean:
public class StatusBean {
private String name;
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
private Date startDate;
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
private Date endDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
And I wrap it in another bean that I use to wrap objects for nice json formatting with messages and stuff:
public class ResponseBean {
private boolean success = false;
private String message;
private Object data;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
In my controller, I set the Status bean inside the response bean with a setData();
Spring serializes this out in JSON format, however the output for the date is not formatting. I am getting the standard "yyyy-MM-DD" format.
Am I doing something wrong? How do I get this to work?
I had the same issue and fixed simply adding #JsonSerialize(as = Date.class) before #JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
With #DateTimeFormat(pattern="dd/MM/yyyy") from
org.springframework.format.annotation.DateTimeFormat worked for me.
I have never tried it but the solution could be to add this annotation in your ResponseBean:
#JsonSerialize(as = StatusBean.class)
private Object data;
unfortunately your Object will become a StatusBean
Possibility not write object with ObjectMapper
new ObjectMapper().writeValueAsString(MyObject);
Full code example
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(new Foo(new java.util.Date())));
System.out.println(objectMapper.writeValueAsString(new Foo(new java.sql.Date(System.currentTimeMillis()))));
}
static class Foo {
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", timezone="EST")
private Date birthdate;
public Foo() {
}
public Foo(Date birthdate) {
this.birthdate = birthdate;
}
public Date getBirthdate() {
return birthdate;
}
}
I've got the following question. I got a little application which saves payments, dates and persons inside a database. Now I got the following POJO class:
public class Payment implements Serializable {
private int id;
private double payment;
private Date datum;
private String usage;
private String category;
private int importance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPayment() {
return payment;
}
public void setPayment(double payment) {
this.payment = payment;
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getImportance() {
return importance;
}
public void setImportance(int importance) {
this.importance = importance;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ID: ");
sb.append(id);
sb.append("\nPAYMENT: ");
sb.append(payment);
sb.append("\nDATE: ");
sb.append(datum);
sb.append("\nUSAGE: ");
sb.append(usage);
sb.append("\nCATEGORY: ");
sb.append(category);
sb.append("\nIMPORTANCE: ");
sb.append(importance);
return sb.toString();
}
}
So, I got also a class for my dates and persons. The question I've got is the following: Should I create for every Table in my database(in Java the Payment.class , Date.class and Person.class) a own transaction/access class which supports an .saveOrUpdate(), .list() or .delete() function?So maybe I got than a PaymentRansaction.class or an PersonTransaction.class.
Thanks for every help :)
It depends.
Do you have one table with transactions, then one model should be sufficient.
Create methods to create the transactions for you depending on Payment or Person.
BUT
If you have more then 1 table go for multiple classess, each table it's own class.