如何使用条件从多个表中获取记录?

时间:2013-11-26 09:23:56

标签: java mysql hibernate-criteria

StuPersonal table-sno,stu_name,gender,FRID;
StuDegree table-sno,degree,dtype,regno,col_name,stP(FRID).

以上是我的表定义(OnetoOne)的关系。 我的pojo课程是

@Entity
public class StuPersonal {
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID") 
private int sno;

@Column(name="NAME") 
private String stu_name;
private int name_verify=0;

@Column(name="GENDER")
private String gender;

@OneToOne(cascade={CascadeType.ALL})
@JoinColumn(name="FRID")
private List<StuDegree> StuDegree;
@Id
private String FRID;

@Entity
public class StuDegree {
@Id
@GeneratedValue(strategy=GenerationType.AUTO) 
@Column(name="sNO")        
private int sno;

@Column(name="DEGREE")
private String degree;

@Column(name="DEGREE_TYPE")
private String dtype;
@Column(name="COLLEGE_NAME") 
private String col_name;
@OneToOne
@JoinColumn(name="FRID")
private StuPersonal stP;

我的主要课程是

Criteria criteria= s. createCriteria(StuDegree.class);
criteria.add(Restrictions.eq("col_name","PSYEC"));
List<StuDegree> colname =(List<StuDegree>) criteria.list();

我使用上面的行来获取Studegree表中的记录;

for (Iterator iterator = colname.iterator(); iterator.hasNext();)
{
   StuDegree stdeg= (StuDegree) iterator.next();
   {
     Criteria criteria1= s.createCriteria(StuPersonal.class);
     criteria.add(Restrictions.eq("stdeg.getFRID()","StuPersonal.getFRID()"));
     List<StuPersonal> stuper=(List<StuPersonal>) criteria1.list();
     System.out.println(stuper.size());
   }
}

我使用上面的代码从Studegree表中使用FRID从StuPersonal表中获取记录,是不是?它不起作用...... Pl建议......

1 个答案:

答案 0 :(得分:1)

如下所示更改您的关系。

变化

@OneToOne(cascade={CascadeType.ALL})
@JoinColumn(name="FRID")
private List<StuDegree> StuDegree;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="FRID")
private List<StuDegree> StuDegree;

你的标准是这样的。它将根据StuDegree sno获取StuPersonal。

Integer snos[] = {1,2,3};
Criteria criteria = s.createCriteria(StuPersonal.class, "sp");
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.createAlias("sp.StuDegree","sd");
criteria.add(Restrictions.in("sd.sno", snos));
List<StuPersonal> stuper= criteria1.list();