trumanblack1025
trumanblack1025

Reputation: 491

Fetching data from many-to-one/one-to-many mapping

I have this 2 tables:

Plan Table

enter image description here

Plan Coverage Table

enter image description here

I want to access all the coverage_description using the plan_code and display it on my jsp page.

This is my code.

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;
    }

}

Thank you so much for your help!!!

Upvotes: 0

Views: 5469

Answers (1)

Angad Bansode
Angad Bansode

Reputation: 923

You can use join fetch to select data from two tables.Plan table have @OneToMany relationship with Plan Coverage entity.So you can write join fetch hql query like.

 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();

Apply foreach loop and get planCoverage entity converage_description one by one.

Upvotes: 1

Related Questions