且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从hibernate中的同一个表的结果中获取表中的数据

更新时间:2023-01-22 11:15:24

您已添加此代码

  String queryString =from Profession where username =:uname; 
Query query = session.createQuery(queryString);
query.setString(uname,uname);

但缺少

 列表< Profession> professionList = query.list(); 
for(Profession:professionList){
System.out.println(获取你需要的东西+ profession.getUsername());
}


I am using Hibernate with spring Rest and i am fetching data from a table. There are two columns in my table username and profession. I created a method in which i am passing a username and getting a profession corresponding to username now i want to search by profession which i got and want to get all usernames who have that profession.

I have fetched profession using a username but i am unable to fetch usernames who have that profession so please suggest me the way to do this.

Here is my Entity class Profession.java

@Entity
@Table(name="user_profession")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Profession implements Serializable {


private static final long serialVersionUID = 1L;


@Id
@GeneratedValue
@Column(name="id")
private long id;

@Column(name="profession")
private String profession;

@Column(name="username")
private String username;


//Getters and setters

public long getId() {
    return id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public void setId(long id) {
    this.id = id;
}

public String getProfession() {
    return profession;
}

public void setProfession(String profession) {
    this.profession = profession;
}

}

Here is my DAO class

@SuppressWarnings("unchecked")
public List<Profession> getProfessionById(String uname) throws Exception {
session = sessionFactory.openSession();
  session.beginTransaction();
  String queryString = "from Profession where username = :uname";
  Query query = session.createQuery(queryString);
  query.setString("uname", uname);
  //List<Profession> queryResult = (List<Profession>) query.uniqueResult();
  session.getTransaction().commit();
  return query.list();

}

Please help me . Thanx in advance

You have added this code

 String queryString = "from Profession where username = :uname";
 Query query = session.createQuery(queryString);
 query.setString("uname", uname);

But missing

  List<Profession> professionList = query.list();
   for(Profession profession: professionList ){
     System.out.println("Get What you need Like"+profession.getUsername());
    }