简体   繁体   中英

Get List of Strings using JPQL

I'm new to Java and still learning, please keep that in mind when answering.

So I want to get a list of strings based on data from a MySQL database using JPQL. More specifically I'm trying to get all unique years from a certain column in a certain table. The data type is a MySQL date (yyyy-mm-dd). The SQL is working perfectly fine! But trying to put it in a List does not do what I expected.

What I have so far:

Servlet:

// em is of the type EntityManager, other queries retrieving objects working fine
List<String> years = em.createQuery("select distinct (date_format(p.birthday, '%Y')) as year from Player p order by year").getResultList();
request.setAttribute("years", years);

View using JSTL:

<c:forEach var="year" items="${years}">
      <p>${year}</p>
</c:forEach>

This gives something like:

[Ljava.lang.Object;@b3d38cd

Use JPA built-in support for dates. For Hibernate:

Query query = em.createQuery("select distinct YEAR(p.birthday) as year from Player p order by year");
List<String> years = query.getResultLits();

For other implementations (JPA 2.1):

Query query = em.createQuery("select distinct FUNCTION('date_format', p.birthday, '%Y') as year from Player p order by year");
List<String> years = query.getResultLits();

I do not think servlet is the best place to have EntityManager inside. I would use DAO pattern Data Access Object Pattern

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