basically I am building a Web app for school and its using Telegram Bot API to send messages to my contacts. On left side of my web page I have contacts div and there is list of all contacts from table in MySQL. Everything works perfect except they are not ordered asc by name.
Controller
@Controller
public class MainController {
@Autowired
private ContactsService contactsService;
@GetMapping("/")
public String allContacts(HttpServletRequest request) {
request.setAttribute("contacts", contactsService.findAll());
request.setAttribute("mode", "MODE_CONTACTS");
return "index";
}
@RequestMapping("/input")
public String input() {
return("input");
}
}
Repository
import org.springframework.data.repository.CrudRepository;
import totelegram.model.Contacts;
public interface ContactsRepository extends CrudRepository<Contacts, Integer>{
}
Service
@Service
@Transactional
public class ContactsService {
private final ContactsRepository contactsRepository;
public ContactsService(ContactsRepository contactsRepository) {
super();
this.contactsRepository = contactsRepository;
}
//@Query("select * from contacts order by name asc")
public List<Contacts> findAll(){
List<Contacts> contacts = new ArrayList<>();
for(Contacts contact : contactsRepository.findAll()) {
contacts.add(contact);
}
return contacts;
}
}
Model
@Entity(name = "contacts")
public class Contacts implements Serializable{
And basically it just has id,name,phone_number, getters/setters, toString. You can see in Service one comment which is exactly something I can’t figure out. Where that @Query needs to be so when you display table on website you get them ordered.
Answer from Abinash Ghosh solved a problem. But others were helpful too.
Thank you all for help.
3
Answers
Try the following code for desc order .
You can do for asc by Sort.Direction.ASC and also
change field name as per need. I have used “id” here.
It should work fine.
For your problem , solution is :
Additionally to the answer from Md Shifatul Isalm you could also create a Repository mehtod like:
Btw you don’t need the additional ArrayList. Just return the values from the Repository:
You can use
JpaRepository
and JPA method naming feature forOrder by
Repository
Service