简体   繁体   中英

Java, MySQL DB, SpringBoot and Thymeleaf. How to pull some fields from 2 different classes to get Data from DB using Thymleaf

I have stucked with the problem: How to retrieve a data from 2 separate classes using Java, MySQL DB and Thymeleaf? I'd like to show content of the messages and user details such as First Name and Second Name plus time on the one web page using Thymleaf. I used to do that with one class but with 2 different classes I have a problem...... :-( My code is below. Please give me some advice:-)

There are classes:

@Entity
@Table(name = "messages")
public class Message {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(length = 400)
    private String message;
    private String uploadDir;
    @DateTimeFormat(pattern = "dd-MMM-yyyy")
    private String localDate;
    @ManyToOne
    @JoinColumn(name = "user_id",
            referencedColumnName = "id"
    )
    private User user;


    public Message(){}
...
getters and setters
}

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String login;
    private String firstName;
    private String lastName;
    private String mail;
    private String password;
    private LocalDate birthDate;
    private String role;
    @OneToMany(mappedBy = "user",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private List<Message> message = new ArrayList<>();

    public User(){}

} 
getters and setters
.......

There are DTO Classes:

public class MessageDTO {

    private UserDTO userDTO;

    private Long id;
    private String message;
    private String uploadDir;
    private String localDate;

getters and setters
......
}

public class UserDTO {

    private Long id;
    private String login;
    private String firstName;
    private String lastName;
    private String mail;
    private String password;
    private LocalDate birthDate;
    private String role;
    private List<Message> message = new ArrayList<>();

getters and setters
......
}


public class MessegeService{
.....

    public List<MessageDTO> getAllMessagesS(){
        return messageRepository
                .findAll()
                .stream()
                .map(message -> modelMapper.map(message, MessageDTO.class))
                .collect(Collectors.toList());
    }
}


public class UserService{

  public List<UserDTO> getAllUsers() {
        return userRepository
                .findAll().stream()
                .map(user -> modelMapper.map(user, UserDTO.class))
                .collect(Collectors.toList());
    }

.....
}

And finally a web page. Here are the problems below for me. I need to pull login, first name, second name from the MySQL DB. The field are in two separate classes. What am I doing wrong?

 <:DOCTYPE html> <html lang="en" xmlns:th="http.//www.thymeleaf:org" xmlns="http.//www.w3:org/1999/html"> <head> <meta charset="UTF-8"> <title>Messages:</title> </head> <body> <div class="container" name="container"> <div class="balloon" name="balloon"> <table class="table" name="text-messages"> <thead class="thead-dark"> <th scope="col" th:width="20px">Id</th> <th scope="col" align="center" th:width="50px">Date & time</th> <th scope="col" align="center">Message</th> <th scope="col" align="center">Message lenght</th> </thead> <tbody> <tr th:each="usermessage, ${userShowMessage} "> <form action="@{/show-messages}" method="post": th:object="${usermessage}"> <td type="number" th.text="${usermessage:id}"></td> <td th.text="${usermessage:localDate}"></td> <td th.text="${usermessage:message}"></td> <td th.text="${usermessage.userDTO.firstName}"></td> <:--That doesn't work. Please give me some advice here --> <td th.text="${usermessage.message.length()}"></td> </form> </tbody> </table> </div> </div> </body> </html>

That line of the code doesn't work: usermessage.userDTO.firstName

How can I retrieve information on one web page using Thymeleaf in that example? Thank you for your advice:-)

This is my Message and User Controllers:

    @Controller
    public class MessageController {
    
        private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
        private MessageService messageService;
    
        public MessageController(MessageService messageService) {
            this.messageService = messageService;
        }
    
        @GetMapping("/useraddcontent")
        public ModelAndView getAddNewMessage(){
            logger.warn("Before add a new message");
            return new ModelAndView("useraddcontent", "userAddMessage", new MessageDTO());
        }
    
        @PostMapping("/useraddcontent")
        public String addNewMessage(@ModelAttribute MessageDTO messageDTO){
            logger.warn("Creating a new message");
            System.out.println(messageDTO.getMessage());
    
            messageService.addMessageS(messageDTO);
            return "redirect:/userpage";
        }
    
        @GetMapping("/show-messages")
        public ModelAndView readMessages(){
            logger.warn("Reading messages");
            List<MessageDTO> messageDTOList = messageService.getAllMessagesS();
           return new ModelAndView("show-messages", "userShowMessage", messageDTOList);
        }
    }


@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping("/finduser")
    public ModelAndView findUser() {
        logger.warn("List the users");
        return new ModelAndView("finduser", "finduser", new UserDTO());
    }

    @GetMapping("/finduserbylastname")
    public ModelAndView findUserByLastName(@ModelAttribute UserDTO userDTO) {
        logger.warn("Find a user by a last name");
        List<UserDTO> userDTOList = userService.findUserByLastName(userDTO.getLastName());
        return new ModelAndView("users", "userList", userDTOList);
    }

    @GetMapping("/users")
    ResponseEntity<List<UserDTO>> findAllUsers() {
        logger.warn("Exposing all users!");
        return ResponseEntity.ok(userService.getAllUsers());
    }

    @GetMapping("/users/{id}")
    ResponseEntity<UserDTO> findUserById(@PathVariable Integer id) {
        logger.warn("Exposing specific user!");
        return userService.getUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping("/users")
    ResponseEntity<User> createUser(@RequestBody UserDTO userDTO) {
        logger.info("Created new user!");
        User result = userService.create(userDTO);
        return ResponseEntity.created(URI.create("/" + result.getId())).build();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM