I have this table:
#Entity
#Table(name = "transaction")
public class Transaction {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "transaction_id")
private Long id;
#Column(name = "user_id", nullable = false)
private Long userId;
#Column(name = "wallet_name", nullable = false)
private String walletName;
#NotNull(message = "Please, insert a amount")
#Min(value = 0, message = "Please, insert a positive amount")
private Double amount;
private String note;
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Column(name = "date")
private LocalDate date;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "wallet_id", nullable = false)
private Wallet wallet;
#Enumerated(EnumType.STRING)
#Column(name = "transaction_type", columnDefinition = "ENUM('EXPENSE', 'INCOME')")
private TransactionType transactionType;
#Nullable
#Enumerated(EnumType.STRING)
#Column(name = "expense_categories", columnDefinition = "ENUM('FOOD_AND_DRINK', 'SHOPPING', 'TRANSPORT', 'HOME'," +
" 'BILLS_AND_FEES', 'ENTERTAINMENT', 'CAR', 'TRAVEL', 'FAMILY_AND_PERSONAL', 'HEALTHCARE'," +
" 'EDUCATION', 'GROCERIES', 'GIFTS', 'BEAUTY', 'WORK', 'SPORTS_AND_HOBBIES', 'OTHER')")
private ExpenseCategories expenseCategories;
#Nullable
#Enumerated(EnumType.STRING)
#Column(name = "income_categories", columnDefinition = "ENUM('SALARY', 'BUSINESS', 'GIFTS', 'EXTRA_INCOME', 'LOAN', 'PARENTAL_LEAVE', 'INSURANCE_PAYOUT', 'OTHER')")
private IncomeCategories incomeCategories;
Because, I want to display transactions by date on page I created a separated class like this:
public class TransactionGroup {
private LocalDate date;
private List<Transaction> transactions;
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public List<Transaction> getTransactions() {
return transactions;
}
public void setTransactions(List<Transaction> transactions) {
this.transactions = transactions;
}
public void setTransactions(String walletName, Double amount, String note, LocalDate date, TransactionType transactionType, ExpenseCategories expenseCategories, IncomeCategories incomeCategories) {
}
}
So, as you can see I have a list of transactions. In my controller where I'm saving transaction I have this:
#PostMapping("/saveIncome/{walletId}")
public String saveIncome(#PathVariable(value = "walletId") long walletId, #Valid Transaction transaction, BindingResult result, Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
long userId = user.getId();
Wallet wallet = walletService.getWalletById(walletId);
TransactionGroup transactionGroup = new TransactionGroup();
boolean thereAreErrors = result.hasErrors();
if (thereAreErrors) {
model.addAttribute("incomeCategories", IncomeCategories.values());
return "income_transaction";
}
transaction.setWallet(wallet);
transaction.setUserId(userId);
transaction.setWalletName(wallet.getWalletName());
transactionGroup.setTransactions(transaction.getWalletName(), transaction.getAmount(), transaction.getNote(), transaction.getDate(), transaction.getTransactionType(), transaction.getExpenseCategories(), transaction.getIncomeCategories());
transactionService.saveIncome(transaction, walletId, userId);
return "redirect:/api/wallet/userWallet/balance/" + userId;
}
This is the thing:
transactionGroup.setTransactions(transaction.getWalletName(), transaction.getAmount(), transaction.getNote(), transaction.getDate(), transaction.getTransactionType(), transaction.getExpenseCategories(), transaction.getIncomeCategories());
And that works fine, transaction is saved. Now when I want to show data from that entity like this:
<div th:each="group : ${transactionGroup}">
<h1 th:text="${group.date}"/>
<div th:each="transaction : ${group.transactions}">
<h2>Amount: <span th:text="${transactions.amount}"></span></h2><br>
<h2>Note: <span th:text="${transactions.note}"></span></h2><br>
<h2>Wallet name: <span th:text="${transactions.walletName}"></span></h2><br>
<h2>Expense Category: <span th:text="${transactions.expenseCategories}"></span></h2><br>
<h2>IncomeCategory: <span th:text="${transactions.incomeCategories}"></span></h2>
<div>
</div>
</div>
</div>
I'm getting a blank page without any transaction data.
I already asked a question similar to this, you can see it from my profile. Idk what to try more and why data is not displayed so far.
Related
I have a Section entity. Section entity has a nested GradeLevel entity annotated with #OneToOne
Section
#Entity
#Setter
#Getter
public class Section{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true, nullable = false)
private String name;
#OneToOne
private GradeLevel gradeLevel;
#Column(columnDefinition = "boolean default true")
private Boolean isActive = true;
#CreationTimestamp
#Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();
#UpdateTimestamp
#Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();
}
GradeLevel
#Entity
#Getter
#Setter
public class GradeLevel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true, nullable = false)
private String code; //GL-01, GL-02...
#Column(unique = true)
private String description; //Kinder 1, Kinder 2, Grade 1....
private String category; //Elementary School, Junior Highschool, Senior Highschool
#Column(columnDefinition = "boolean default true")
private Boolean isActive = true;
#CreationTimestamp
#Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();
#UpdateTimestamp
#Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();
}
The #OneToOne GradeLevel gradeLevel; creates a foreign key in the Section table that references to GradeLevel's ID column.
The table looks like this:
Now if I want to update just the name of the Section and pass just the Section ID and new Section Name without the GradeLevel ID request sample below,
{
"id" : 1,
"name" : "Venus" }
The compiler complains about a null GradeLevel ID
org.hibernate.HibernateException: identifier of an instance of com.jordan.cdoautoformsettingsservice.entities.GradeLevel was altered from 1 to null...
This gives me the impression that when we have nested JPA entities with #OneToOne (or #OneToMany...), we are required to provide the ID of the nested Entity. In this case, it wants the ID of the GradeLevel
I fails to complete the UPDATE operation.
ServiceImpl.java (UPDATE method) below
#Override
public Section updateSection(Section request) throws Exception {
logger.debug("request : "+request);
Long sectionId = request.getId();
Optional<Section> optionalSection = sectionRepo.findById(sectionId); //retrieve the section we want to update
if(!optionalSection.isPresent()){
throw new Exception("Section with ID: "+request.getId()+ "is NOT FOUND");
}
GradeLevel gradeLevel = optionalSection.get().getGradeLevel();
gradeLevel.setId(request.getGradeLevel().getId());
logger.debug("GradeLevel Properties: ");
logger.debug("GradeLevel ID: "+gradeLevel.getId());
logger.debug("GradeLevel CODE: "+gradeLevel.getCode());
logger.debug("GradeLevel DESCRIPTION: "+gradeLevel.getDescription());
logger.debug("GradeLevel CATEGORY: "+gradeLevel.getCategory());
Section section = optionalSection.get();
section.setName(request.getName()); //replace current section name with section name FROM REQUEST
section.setDateLastUpdated(request.getDateLastUpdated());
section.setIsActive(request.getIsActive());
section.setGradeLevel(gradeLevel);
return sectionRepo.save(section);
}
I'd appreciate any suggestion or thoughts.
Thank you.
this is error due to auto generated entity will generate new section id at every time if you add a constructor in Section.java that has argument id value. then save function work fine
Section.java
package com.example.updatehibernate.entity;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
public class Section{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true, nullable = false)
private String name;
#OneToOne
private GradeLevel gradeLevel;
#Column(columnDefinition = "boolean default true")
private Boolean isActive = true;
#CreationTimestamp
#Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();
#UpdateTimestamp
#Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GradeLevel getGradeLevel() {
return gradeLevel;
}
public void setGradeLevel(GradeLevel gradeLevel) {
this.gradeLevel = gradeLevel;
}
public Boolean getActive() {
return isActive;
}
public void setActive(Boolean active) {
isActive = active;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public LocalDateTime getDateLastUpdated() {
return dateLastUpdated;
}
public void setDateLastUpdated(LocalDateTime dateLastUpdated) {
this.dateLastUpdated = dateLastUpdated;
}
public Section(Long id, String name, GradeLevel gradeLevel, Boolean isActive, LocalDateTime dateCreated, LocalDateTime dateLastUpdated) {
this.id = id;
this.name = name;
this.gradeLevel = gradeLevel;
this.isActive = isActive;
this.dateCreated = dateCreated;
this.dateLastUpdated = dateLastUpdated;
}
public Section(Long id, String name) {
this.id = id;
this.name = name;
}
public Section() {
}
}
I'm working with my hospital project with java spring and angular.
When I try to insert a new Doctor(Medico.java) in a Hospital (called StrutturaSanitaria.java)
with a #OneToOne Relationship mapping a customed relation class, called MedicoStrutturaSanitaria.java. This class is created because I needed an extra column which is dataAssunzione (hireDate).
As long as I add just the Doctor the Post request works just fine, it adds the instance of the Doctor in the database (I'm using MySql).
THE PROBLEM IS: When I try to add the relation instance to the DB for every value, except for the hireDate, it gives me null value.
I'm testing the post requests with Postman.
here is the code
Medico.java
#Entity
#Table(name = "medico")
public class Medico
{
#Id
private String codiceFiscale;
#Column(nullable = false)
private String nome;
#Column(nullable = false)
private String cognome;
#Column(nullable = false)
private String genere;
#Column(nullable = false)
private LocalDate dataNascita;
#Column(unique = true, nullable = false)
private String email_uno;
#Column(unique = true, nullable = false)
private String cellulare_uno;
#Column(nullable = false)
private String indirizzo;
#Column(nullable = false)
private String citta;
#Column(nullable = false)
private String provincia;
#OneToOne
private MedicoStrutturaSanitaria medicoStrutturaSanitaria;
public Medico()
{}
public Medico(String codiceFiscale, String nome, String cognome, String genere,
LocalDate dataNascita, String email_uno, String cellulare_uno,
String indirizzo, String citta, String provincia, MedicoStrutturaSanitaria medicoStrutturaSanitaria)
{
this.codiceFiscale = codiceFiscale;
this.nome = nome;
this.cognome = cognome;
this.genere = genere;
this.dataNascita = dataNascita;
this.email_uno = email_uno;
this.cellulare_uno = cellulare_uno;
this.indirizzo = indirizzo;
this.citta = citta;
this.provincia = provincia;
this.medicoStrutturaSanitaria = medicoStrutturaSanitaria;
}
//getters and setters
MedicoStrutturaSanitaria.java
#Entity
#Table(name = "medico_struttura_sanitaria")
#IdClass(MedicoStrutturaSanitariaID.class)
public class MedicoStrutturaSanitaria
{
#Id
#JoinColumn(name="medico",referencedColumnName = "codiceFiscale")
#ManyToOne
private Medico medico;
#Id
#JoinColumn(name="struttura_sanitaria", referencedColumnName = "codice")
#ManyToOne
private StrutturaSanitaria strutturaSanitaria;
#Id
private LocalDate dataAssunzione;
public MedicoStrutturaSanitaria()
{}
public MedicoStrutturaSanitaria(Medico medico, StrutturaSanitaria strutturaSanitaria, LocalDate dataAssunzione)
{
this.medico = medico;
this.strutturaSanitaria = strutturaSanitaria;
this.dataAssunzione = dataAssunzione;
}
//getters and setters
Postman request. The object passed as parameters are existing instances
Post request method. As you can see all the parameters thar are passed are null, excpet for hireDate
UPDATE 1
THIS IS MY CONTROLLER
#PostMapping("/inserisci-medico-struttura-sanitaria")
public ResponseEntity<MedicoStrutturaSanitaria> inserisciMedicoStrutturaSanitaria(#RequestBody MedicoStrutturaSanitaria medicoStrutturaSanitaria)
{
System.out.println("Inserendo medico struttura");
try
{
System.out.println("Inserendo medico");
this.medicoStrutturaSanitariaRepository.save(medicoStrutturaSanitaria);
return ResponseEntity.ok(medicoStrutturaSanitaria);
}
catch (Exception exception)
{
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
Before saving relation between doctors and Hospitals. Check if that hospital and Doctor exist in Database or not.(If doesn't not exists create a new one).
If not recommend to send the object of Joining table over the Post request.
Instead 1ts send a two get requests(Get Doctors and Hospitals).
Send one post request(addDoctorInHospital) with doctor_id and hostipal_id and date with provided by the server.
(This question has a spanish version: Pregunta español StackOverflow)
Hello,
im creating a API-REST with springboot, hibernate ...
In one controller, im returning one entity, the point is, when i do this:
Empresa company= empresaManager.findById(2L);
return company;
returns exactly what i expect, (the object company has a list of students, and has only 2 vinculated).
But when instead of use a number, what i do is get the students, and afterwards, return the company of the students, the company that its returning me comes with 12 students (6 times repeated each student)
String token = request.getHeader("Authorization");
token = token.replace("Bearer ", "");
Usuario usuario = tokenManager.getUsuarioFromToken(token);
Long id = usuario.getEmpresa().getIdempresa();
Empresa empresaOriginal = empresaManager.findById(id);
return empresaOriginal;
Any chance you know why is happenning this ?
This is how should return the object company:
And this is how im actually getting it:
From here, to down, is what is asked in comments
This is my user entity :
#Entity
#Table(name = "usuario")
public class Usuario {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idusuario")
private Long idusuario;
#Column(name = "nombre", length = 30, nullable = false)
private String nombre;
#Column(name = "email", length = 80, nullable = false)
private String email;
#JsonIgnore
#Column(name = "contraseña", length = 300, nullable = false)
private String contraseña;
#JsonIgnore
#ManyToOne
#JoinColumn(foreignKey = #ForeignKey(name = "empresa_idempresa"), name = "empresa_idempresa")
private Empresa empresa;
#OneToMany(mappedBy = "usuario", orphanRemoval = true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Fichaje> fichajes;
public Usuario() {
}
public Empresa getEmpresa() {
return empresa;
}
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
}
This is my Company entity:
#Entity
#Table(name = "empresa")
public class Empresa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idempresa")
private Long idempresa;
#Column(name = "nombre", length = 100, nullable = false)
private String nombre;
#Column(name = "contacto", length = 300, nullable = false)
private String contacto;
#Column(name = "fecha_inicio_practicas", columnDefinition = "DATE")
private LocalDate inicioPracticas;
#Column(name = "direccion", length = 100)
private String direccion;
#Column(name = "foto_empresa")
private String fotoEmpresa;
#OneToMany(mappedBy = "empresa", orphanRemoval = true, cascade = CascadeType.ALL)
private List<EmpresaTieneDia> empresaTieneDias;
#OneToMany(mappedBy = "empresa", orphanRemoval = false, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Usuario> estudiantes;
public Empresa() {
}
public Long getIdempresa() {
return idempresa;
}
public void setIdempresa(Long idempresa) {
this.idempresa = idempresa;
}
public List<Usuario> getEstudiantes() {
return estudiantes;
}
public void setEstudiantes(List<Usuario> estudiantes) {
this.estudiantes = estudiantes;
}
}
This is the findById:
(Service or Manager)
public Empresa findById(Long id) {
return this.empresaRepository.findByIdempresa(id);
}
(Repository or DAO)
public interface EmpresaRepository extends CrudRepository<Empresa, Long> {
Empresa findByIdempresa(Long id);
}
SOLVED
I had to change my listo of users from a List<Usuario> to a Set<Usuario>.
Anyways, I understand why it fixes it using a Set (cause doesn't let duplicated values in it).
Anyways, if someone could try to explain my why in the first moment I'm having 6 times duplicated every item in the list i would apreciate it.
Thanks !! :D
in my code i have two entities BusDetails and User. The User and the BusDetails has many to many relationship. Whenever i try to book bus, the data is saved in the join table in database but i get this exception: Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is java.lang.IllegalArgumentException: Could not parse date: it is not exactly10characters long]]
User Table:
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int u_id;
#Column
#NotEmpty(message = "Name cannot be empty")
private String name;
#Column
#NotEmpty(message = "Username cannot be empty")
private String userName;
#Column
#NotEmpty(message = "please enter number")
#Size(min = 10,max = 10, message = "10 digits required")
private String number;
#Column
#NotEmpty
#Size(min=8,message = "Minimum 8 characters required")
private String password;
#ManyToMany(cascade = CascadeType.MERGE,fetch = FetchType.EAGER)
#JoinTable(name = "user_role",joinColumns = #JoinColumn(name = "u_id"), inverseJoinColumns = #JoinColumn(name = "r_id"))
public Set<Role> roles;
#ManyToMany(cascade = CascadeType.PERSIST,fetch = FetchType.EAGER)
#JoinTable(name = "user_busdetails", joinColumns = #JoinColumn(name = "u_id") , inverseJoinColumns = #JoinColumn(name = "bus_Id"))
public Set<BusDetails> bus = new HashSet<BusDetails>();
//gettersAndSetters
BusDetails:
#Entity
#Component("BusDetails")
public class BusDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int bus_Id;
#Column
public String fromDestination;
#Column
public String toDestination;
#Column
#DateTimeFormat
#Temporal(TemporalType.DATE)
private Date date;
#Column
private String travels;
#Column
private String bus_Type;
#Column
private String seats_Available;
#Column
public String fare;
#Column
private String departure;
#ManyToMany(fetch = FetchType.EAGER,mappedBy = "bus")
#JsonIgnore
public Set<User> user = new HashSet<User>();
//gettersAndSetters
BookController:
#PostMapping("/bookbus")
#ResponseBody
public BusDetails bookBus(#ModelAttribute BusDetails bus) {
System.out.println(bus.getDate());
return busDetail.bookBus(bus);
}
#InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor( Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-
MM-dd"), true, 10));
}
BookService:
public BusDetails bookBus(BusDetails bus) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipleName = authentication.getName();
User user = userRepo.findByUserName(currentPrincipleName);
user.getBus().add(bus);
System.out.println(user);
System.out.println(bus);
userRepo.save(user);
return bus;
}
Because you used #ModelAttribute in the controller means all parameters is pass in String format.
In your case is to format from String to Date.
#Entity
#Component("BusDetails")
public class BusDetails {
//...
#Column
private Date date;
//setter(can add or modify) should be custom like below :
public void setDate(String date){
try {
this.date = new SimpleDateFormat("yyyy-MM-dd").parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
// ...getter & setter
}
Convert Date Parameters at the Application Level
#Configuration
class DateTimeConfig {
#Bean
public FormattingConversionService conversionService() {
DefaultFormattingConversionService conversionService =
new DefaultFormattingConversionService(false);
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setDateFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));
registrar.registerFormatters(conversionService);
// other desired formatters
return conversionService;
}
}
First, we create DefaultFormattingConversionService with a false parameter, which means Spring will not register any formatters by default.
And then, we manually register new patterns for date and date-time formats in the DateTimeFormatterRegistrar object.
I have 3 objects: User, Comment and StatusUpdate(news). This is the User...
#Entity
#Table(name = "users")
#PasswordMatch(message = "{register.repeatpassword.mismatch}")
public class SiteUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "email", unique = true)
#Email(message = "{register.email.invalid}")
#NotBlank(message = "{register.email.invalid}")
private String email;
#Transient
#Size(min = 5, max = 15, message = "{register.password.size}")
private String plainPassword;
#Column(name = "password", length = 60)
private String password;
#Column(name = "enabled")
private Boolean enabled = false;
#NotNull
#Column(name = "firstname", length = 20)
#Size(min = 2, max = 20, message = "{register.firstname.size}")
private String firstname;
#NotNull
#Column(name = "surname", length = 25)
#Size(min = 2, max = 25, message = "{register.surname.size}")
private String surname;
#Transient
private String repeatPassword;
#Column(name = "role", length = 20)
private String role;
public SiteUser() {
}
Here comes the StatusUpdate(you can call it piece of news or article). That has a site user that is the one who has created that article.
#Entity
#Table(name = "status_update")
public class StatusUpdate {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Size(min=5, max=255, message="{addstatus.title.size}")
#Column(name = "title")
private String title;
#Size(min=5, max=5000, message="{addstatus.text.size}")
#Column(name = "text")
private String text;
#Column(name = "added")
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss")
private Date added;
#OneToOne(targetEntity = SiteUser.class)
#JoinColumn(name="user_id")
private SiteUser siteUser;
#PrePersist
protected void onCreate() {
if (added == null) {
added = new Date();
}
}
public StatusUpdate() {
}
And the Comment which can be done by any registered user, right? As you will notice the Comment has no User object to avoid circular references.
#Entity
#Table(name = "comments")
public class Comment {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
#JoinColumn(name = "statusupdateid")
private StatusUpdate statusUpdate;
#Column(name = "commenttext")
private String commenttext;
#Column(name = "commentdate")
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = "yyyy/MM/dd hh:mm:ss")
private Date commentdate;
#Column(name = "userid")
private Long userid;
public Comment() {
}
Now I would like to show in my JSP an article, with all the related comments and each of them belong to a different user. Can I use a HashMap to relate the users and their comments? I do not see how.
#RequestMapping(value ="/viewonestatus/{id}")
public ModelAndView viewOneStatus(#PathVariable("id") Long id) {
StatusUpdate status = statusUpdateService.get(id);
int countComments = commentService.countStatusComments(status);
List<Comment> comments = commentService.readAllComments(status);
ModelAndView modelAndView = new ModelAndView();
for (Comment comment: comments){
SiteUser user = userService.get(comment.getUserid());
modelAndView.getModel().put("user", user);
}
modelAndView.getModel().put("commentscounter", countComments);
modelAndView.getModel().put("status", status);
modelAndView.getModel().put("comments", comments); //!!
modelAndView.setViewName("app.viewonestatus");
return modelAndView;
}
As you expect, when my JSP shows just one user (the last one) for all the comments, but I can not relate all the Comments with the corresponding Users
<table class="table table-hover">
<c:forEach var="comment" items="${comments}">
<tr>
<td>
<div class="col-sm-2 sm-margin-bottom-40">
<img class="img-responsive profile-img margin-bottom-20" id="profilePhotoImage" src="/profilephoto/${comment.userid}" />
</div>
<h4>
${user.firstname} ${user.surname}
<span>
<!-- <span>${counterUserMap[comment.key]}</span> -->
5 hours ago / Reply
</span>
</h4>
<p>
<fmt:formatDate pattern="EEEE d MMMM y 'at' H:mm:ss" value="${comment.commentdate}" />
</p>
<p>${comment.commenttext}</p>
</td>
</tr>
</c:forEach>
I do not want to use JSON. I'm thinking about an anonymous class with all the stuff inside. Well, I'm open to your thoughts. Thanks.
Shokulei answer was the solution:
Since you have the userid, you can link it using the #ManyToOne annotation. This would be the most ideal way. But if you really don't want to link them, then you can create a new #Transient SiteUser siteUser; attribute in Comment class. And then in your for loop, you can use comment.setSiteUser(user); instead of modelAndView.getModel().put("user", user);. Hope this will help.
Thanks Shokulei