Search code examples
javapersistencenamed-query

Why in all tutorials write named query in the entity class. It's the logic part


it is good practice don't have any logic in POJO classes, but NamedQuery contains some logic


Solution

  • its more of a 'generated code' problem that you have here. Most actual developers don't write Named queries in Entity classes at all. It doesn't make sense to put then there. But when you generate entity classes using a code generator, it places a 'find all' type of named query at the top always. This is primarily because code generator don't know what kind of named queries doe you need. They guess a 'find all' one fits all but personally I have never user a find all kind of query on any entity directly. There are always some predicates involved.

    For me the best place for named queries is:

    • For large numbers of them: an XMl file
    • For small numbers of them use a java class and use annotations.