简体   繁体   中英

How to limit to 1 item on Left join query with JPA?

Here's my use case :

public class User extends Model {}

public class TableA extends Model {
    @OneToMany
    public List<TableB> tableBs;

    @ManyToOne
    public AnObject anObject;
}

public class TableB extends Model {
    @ManyToOne
    public TableA tableA;

    @ManyToOne
    public User user;

    public String status;
}

The user get a list of TableA entries based on an instance of AnObject. I'd like to show this user if TableA is new or not.

(note that TableB is acting like an:n table for User and TableA, I can't integrate it to TableA)

To say if it is new, it depends on TableB. For that, I have two options :

  • Either creating TableB when I create TableA, but with the status at NEW or No
  • Or not creating TableB for that user. If the link is missing for that user, that mean it's new. (doing it, I could remove the column status)

(actions depends on "new", it's not just a label to show).

Now, in my JPA request, how can I indicate if, for that member, TableA entry is new or not ?

The simple way would be to get the list of TableA, and then go through the List to check if there is the User in it (a method like isUserInTableB(User user) )

But is it possible to do it with JPA, for example by having only one item in the List, that would be the User, or empty if this user is not linked ?

(I hope I'm clear, it's not so much in my head :/)

Thank you really much for your help, I appreciate!

The tableBs list is an attribute not a result of a query so you can't load it partially.

What you can do with one query is retrieve the tableB instance based on the tableA instance and the user instance. Something like

public static TableB findByTableAAndUser(TableA, tableA, User user) {
    return find("select tableB from TableB tableB where tableB.tableA=? and tableB.user=?", tableA, user).first();
}

Another way, if you want to have an "isNew" method on a tableA instance is to fetch the tableBs collection when you load tableA and juste iterate through tableBs instances in the isNew method. Something like

public boolean isNew(User user) {
    for (TableB tableB : tableBs) {
        if (tableB.user.equals(user)) {
            return true;
        }
    }
    return false;
}

your findByIdWithTableBs method could be

public static TableA findByIdWithTableBs(Long id) {
    return find("select tableA from TableA tableA fetch join tableA.tableBs where tableA.id=?", id).first();
}

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