Spring Boot, HTML, MySQL. Вывод записей из БД на HTML страничку от последней к первой. (На картинке суть)

Controller

import com.company.blog.models.*;
import com.company.blog.repo.ActualInformationRepository;
import com.company.blog.repo.EventRepository;
import com.company.blog.repo.RequestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.Timestamp;

@Controller
public class AccountClientControllers {
    @Autowired
    private ActualInformationRepository actualInformationRepository;

@GetMapping("/ActualInformation")
    public String ViewActualInformation(Model model) {
        Iterable<ActualInformation> ActualInformations = actualInformationRepository.findAll();
        model.addAttribute("ActualInformations", ActualInformations);
        return "ClientHTML/actualInformation";
    }
}

Model

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class ActualInformation {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    String text;

    public ActualInformation(String text) {
        this.text = text;
    }
    public ActualInformation(){

    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}

Repository

import com.company.blog.models.ActualInformation;
import org.springframework.data.repository.CrudRepository;

public interface ActualInformationRepository extends CrudRepository<ActualInformation, Long> {
}

HTML

<section class="AllActualInformation">
    <h3 >Актуальная информация</h3>
    <div th:each="el : ${ActualInformations}" class="editInformation">
        <div>
            <p th:text="${el.text}" class="size" name="text" id="text" placeholder="Текст"></p>
        </div>


        <hr class="hh1">
    </div>
</section>

Доброго времени суток!

Подскажите пожалуйста как и что сделать и прописать, чтобы записи из БД с актуальной информацией выводились наоборот. То есть на HTML страничке сверху была новая запись, а вниз уходили ранее добавленные записи.

Сейчас выводится как показано на картинке. А нужно, чтобы запись № 1 уходила вниз при добавлении новых записей.

введите сюда описание изображения


Ответы (1 шт):

Автор решения: Roman Konoval

Добавьте в репозиторий метод:

public interface ActualInformationRepository extends CrudRepository<ActualInformation, Long> {
  List<ActualInformation> findAllByOrderByIdDesc();
}

И потом используйте его в контроллере:

Iterable<ActualInformation> ActualInformations =
        actualInformationRepository.findAllByOrderByIdDesc();        

Это работает таким образом, что spring (а точнее spring data), позволяет определять методы в репозиториях, которые реализуют поиск. Есть определенные правила, как именовать методы чтобы добавлять определенные аспекты поведения к запросам, которые будут выполнятся, когда такой метод вызывается.

Это позволяет с помощью правил именования добавлять:

  1. фильтрацию по полям
  2. сортировки
  3. накладывание ограничений (например, вернуть первые 10 записей)

В данном случае нас интересует сортировка. Для этого добавили ByOrder + ById + Desc чтобы была сортировка по убыванию id.

→ Ссылка