I have a LEFT JOIN, which looks like this:
entityManager.createQuery("SELECT t FROM Template t LEFT JOIN t.messages c WHERE t.client.hostname=:ch GROUP BY t.id, t.subject, t.text, t.client ORDER BY count(c)").setParameter("ch", client.getHostname()).getResultList();
I don't see a join clause in your query. Without a join clause, you will get a cartesian product, and the performance will degrade exponentially as the tables grow.
You need something like "Template.id = message.id" to avoid a cartesian product.
You can see examples of what I'm talking about here: