java - Fetch data using single select statement in HQL (One to many relationsheep) -
i have 2 entities student , college. single college has multiple student.
@entity public class college { @id @generatedvalue private int collegeid; private string collegename; public int getcollegeid() { return collegeid; } public void setcollegeid(int collegeid) { this.collegeid = collegeid; } public string getcollegename() { return collegename; } public void setcollegename(string collegename) { this.collegename = collegename; } } @entity public class student { @id @generatedvalue private int studentid; private string studentname; @manytoone(cascade = cascadetype.all) private college college; public int getstudentid() { return studentid; } public void setstudentid(int studentid) { this.studentid = studentid; } public string getstudentname() { return studentname; } public void setstudentname(string studentname) { this.studentname = studentname; } public college getcollege() { return college; } public void setcollege(college college) { this.college = college; } }
now want select students collegeid = 1. can achieve single select query using native sql:
select * student collegeid = 1
i'm not able achieve same single select query using hql. possible? if yes how?
utility class :
public class manytoone { public static void main(string[] args) { entitymanagerfactory emf = persistence.createentitymanagerfactory("org.hibernate.examples"); entitymanager em = emf.createentitymanager(); college college1 = new college(); college1.setcollegename("college1"); college college2 = new college(); college2.setcollegename("college2"); student student1 = new student(); student1.setstudentname("std1"); student1.setcollege(college1); student student2 = new student(); student2.setstudentname("std2"); student2.setcollege(college2); student student3 = new student(); student3.setstudentname("std3"); student3.setcollege(college1); student student4 = new student(); student4.setstudentname("std4"); student4.setcollege(college1); em.gettransaction().begin(); em.persist(college1); em.persist(college2); em.persist(student1); em.persist(student2); em.persist(student3); em.persist(student4); em.gettransaction().commit(); em.close(); em = emf.createentitymanager(); em.gettransaction().begin(); string querystring = "select student "+student.class.getname()+" student student.college.collegeid = 1"; query query = em.createquery(querystring); list<student> students = query.getresultlist(); em.gettransaction().commit(); em.close(); emf.close(); } }
generated queries:
hibernate: select student0_.studentid studentid1_1_, student0_.college_collegeid college_collegeid3_1_, student0_.studentname studentname2_1_ mevada.student student0_ student0_.college_collegeid=1 hibernate: select college0_.collegeid collegeid1_0_0_, college0_.collegename collegename2_0_0_ mevada.college college0_ college0_.collegeid=?
hql
select * student s s.college.collegeid = 1
Comments
Post a Comment