hibernate查询部分字段需要注意

类User有如下属性:
      
public class User {
	
	private String userId;
	
	private String username;
	
	private String password;

	public User() {
		super();
	}

	public String getUsername() {
		return username;
	}

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

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}
	
}






在Hibernate查询中,查询所有字段与查询部分字段的区别

查询所有字段,可以直接使用如下查询方式:
       
Session session = sessionFactory.getCurrentSession();
        String hql = "from User t";
        List<User> s = session.createQuery(hql).list();


查询部分字段,使用如下方式:

   1.在User类中加入有参构造:
  
   
 public User(String userId,String username) {
	    this.userId = userId;
	    this.username = username;
	    
	}


    2.在HQL中new 包名.类名(部分字段名):

       
Session session = sessionFactory.getCurrentSession();
        String hql = "select new com.hm.pojo.User(t.userId,t.username) from User t";
        List<User> s = session.createQuery(hql).list();

   

猜你喜欢

转载自ttling.iteye.com/blog/2039819