从多对一/一对多映射中获取数据

时间:2018-09-24 00:27:38

标签: hibernate spring-boot jpa one-to-many many-to-one

我有这2张桌子:

计划表

enter image description here

计划覆盖率表

enter image description here

我想使用plan_code访问所有coverage_description,并将其显示在我的jsp页面上。

这是我的代码。

Plan.java

@Entity
@Table(name="plan")
public class Plan {
    /....

    @OneToMany(targetEntity=PlanCoverage.class, mappedBy="plan",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    private List<PlanCoverage> planCoverage;

    public List<PlanCoverage> getPlanCoverage() {
        return planCoverage;
    }

    public void setPlanCoverage(List<PlanCoverage> planCoverage) {
        this.planCoverage = planCoverage;
    }

    private String coverage_description;

    public String getCoverage_description() {
        return coverage_description;
    }

}

PlanCoverage.java

@Entity
@Table(name="plan_coverage")
public class PlanCoverage {

    @ManyToOne()
    @JoinColumn(name="plan_code", referencedColumnName = "plan_code",insertable=false, updatable=false)
    private Plan plan;

    public Plan getPlan() {
        return plan;
    }

    public void setPlan(Plan plan) {
        this.plan = plan;
    }

}

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用联接获取从两个表中选择数据。计划表与Plan Coverage实体具有@OneToMany关系,因此您可以编写联接获取hql查询,例如。

 String hql = "select p from Plan p join fetch p.planCoverage where p.planCode=:code";
   List<Plan> plans = this.sf.getCurrentSession().createQuery(hql).setParameter("code",plan_code).list();

应用foreach循环并一一获取planCoverage实体converage_description。