How to make a sample at JPA



  • We need a sample for JSON. I have about 30 fields in my facility. I need to get five out of them. For example, the name, name and address of the laser.

    I want to get a "Vasya," "surname" "Pupkin," "address"

    I make a sample like:

    @Query(value = "SELECT user.name, user.surname, user.address FROM User user")
    List<Task> findAll();
    

    I'm out of "["Vasya,""Pupkin," "Main str 9"] that is, no field names.

    It's not possible to dissolve it without the names of the fields. How? @JsonIgnore is not an option.



  • Select the field by number. You know what order they're going to do if you're asking for it.

    List<Object[]> users = em.createQuery(...).getResultList();
    for (Object[] u : users) {
        System.out.println(u[0]); // name
        ...
    }
    

    Another option is to use the operation. NEW and designer.
    Determine for your projection (sample of fields are often referred to as a projection) a class with a designer with parameters corresponding to sample fields:

    package a.b.c;
    

    public class UserPr {
    private String name; // поля
    ...

    public UserPr(String name, String surname, ...) // конструктор с полями как в запросе        
    
    public String getName() {
        return name;
    }    
    ...     
    

    }

    You don't have to make private fields and ghetters. You can just use the public fields.

    Now the surgery. NEW
    JPQL will look like this:

    String query = "SELECT NEW a.b.c.UserPr(user.name, user.surname, user.address) FROM User user"

    Complete class name required a.b.c.UserPr

    As a result of this request, List<UserPr>:

    List<UserPr> users = em.createQuery(query).getResultList();
    for (UserPr u : users) {
    System.out.println(u.getName());
    ...
    }

    Thus, the results of the request can be mixed in all classes with a suitable designer.
    You can even use the same. UserIf you make him the right designer! Only the resulting facilities will not be considered Entity with all the following.

    I'm not gonna sign in detail, I'm just gonna mention it.
    For negative requests, exactly. I don't remember JPQL.
    Sometimes for these classes, it's got to be a little cranky.
    Annotations @SqlResultSetMapping It allows each sample field to be translated into a class field ( the exact design parameter).

    As opposed to println getting your JSON, I hope you do it yourself.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2