如何查询Spring JPA中三个实体之间的关系

时间:2016-05-13 07:10:37

标签: java spring hibernate jpa

我正在处理我的高级项目,我的团队的客户要求我们使用Spring Boot,我们都不熟悉。现在,我正在制作一个分页的可排序列表,该列表将向登录用户显示与其用户ID相关联的访问。我们的模型如下:

@Entity
@Table(name="users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonView(View.User.class)
    private long id;

    @Column(name = "full_name")
    @NotNull
    @JsonView(View.User.class)
    private String fullName;

    @Column(name = "is_manager")
    @NotNull
    private boolean isManager;

    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "users")
    private Set<Visit> visits;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="user")
    private Set<VisitEntry> visitEntries;

-

@Entity
@Table(name="visits")
public class Visit implements Iterable<VisitEntry> {
    static final public String INSPECTION_TYPE_FULL = "Full Inspection";

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonView(View.Visit.class)
    private long id;

    @Column(name = "visit_number")
    @NotNull
    @JsonView(View.Visit.class)
    private int visitNumber;

    @ManyToOne(cascade=CascadeType.ALL)
    @NotNull
    @JsonView(View.Visit.class)
    private Provider provider;

    @ManyToOne(cascade=CascadeType.ALL)
    private User leader;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name="users_visits",
            joinColumns={@JoinColumn(name="VISIT_ID")},
            inverseJoinColumns = @JoinColumn(name = "USER_ID")
    )
    private Set<User> users;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="visit")
    @JsonView(View.Visit.class)
    @JsonManagedReference
    private List<VisitEntry> visitEntries = new ArrayList<>();

    @Column(name = "open")
    @NotNull
    private boolean open;

-

@Entity
@Table(name="visit_entries")
public class VisitEntry {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonView(View.Visit.class)
    private long id;

    @Column(name = "pre_inspection")
    @JsonView(View.Visit.class)
    private int preInspectionPrepHours;

    @ManyToOne(cascade = CascadeType.ALL)
    @NotNull
    @JsonBackReference
    private Visit visit;

    @ManyToOne(cascade=CascadeType.ALL)
    @NotNull
    @JsonView(View.Visit.class)
    private User user;

因此,我们访问的访问条目很多,每个访问条目都有一个用户。我需要的是让所有访问与用户相关联。

不幸的是,在每次阅读各种教程后,我的队友和我都非常困惑,并且对如何做到这一点有完全不同的想法,其中没有一个真正起作用。基于这个问题(Joining two table entities in Spring Data JPA),我创建了访问和用户之间的关系,认为我可以在我的存储库中使用Page<Visit> findByUsers(User user, Pageable pageable);,但我总是得到一个空集。所以现在我们最终得到了这条丑陋的代码,它可以分页,但不进行任何排序:

@RequestMapping(value="/visits/{pageNum}/{sort}/{direction}", method= RequestMethod.GET)
public String visits(@PathVariable int pageNum,
                     @PathVariable String sort,
                     @PathVariable String direction,
                     Model model,
                     HttpServletRequest request) {
    User currentUser = getUser(request);

    final int pageSize = 10;
    Pageable pageable;

    //get direction info from parameters and convert to Sort.Direction enum
    if (direction.compareTo("asc") == 0)
        pageable = new PageRequest(pageNum - 1, pageSize, Sort.Direction.ASC, sort);
    else
        pageable = new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, sort);

    //get pageable list of visits dependant on current user
    Page<Visit> visits;

    if(currentUser.isManager()) {
        visits = visitRepo.findAll(pageable);
    }
    else {
        //visits = visitRepo.findByUser_Id(currentUser, pageable);
        List<VisitEntry> entries = visitEntryDao.findByUser(currentUser);
        List<Visit> visitList = new ArrayList<>();
        for (int x = 0; x < entries.size(); x++) {
            visitList.add(entries.get(x).getVisit());
        }

        int offset = (pageNum - 1) * pageSize;
        int offsetEnd = offset + 10;
        if (offsetEnd > visitList.size())
            offsetEnd = visitList.size();

        List<Visit> content = visitList.subList(offset, offsetEnd);
        visits = new PageImpl<Visit>(content, pageable, visitList.size());
    }

    edu.ewu.timetrackers.util.Page[] pages = new edu.ewu.timetrackers.util.Page[visits.getTotalPages()];

    for (int i = 0; i < visits.getTotalPages(); i++) {
        pages[i] = new edu.ewu.timetrackers.util.Page(i + 1, pageNum == i + 1);
    }

    //add visit and number of pages to model
    model.addAttribute("visits", visits);
    model.addAttribute("pageCount", visits.getTotalPages());
    //add sorting and paging info to model
    model.addAttribute("pageNum", pageNum);
    model.addAttribute("sort", sort);
    model.addAttribute("direction", direction);
    model.addAttribute("pages", pages);

    //below attributes determine previous and next buttons for pagination
    if (pageNum > 1)
        model.addAttribute("notFirst", pageNum - 1);
    if (pageNum < visits.getTotalPages())
        model.addAttribute("notLast", pageNum + 1);

    return "visits";
}

任何人都可以清理正确的方法吗?我们已经尝试过四处寻找并且没有找到我们社区中使用Spring的任何人,这可以帮助我们理解我们在这里缺少的东西。

谢谢!

0 个答案:

没有答案