按字段hibernate选择

时间:2014-03-03 12:10:55

标签: java sql hibernate

我有这样的结构

package logic;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="users")
public class user {
    private Long id;
    private String name;
    private String pass;

    public user(){
        name = null;
    }

    public user(user u){
        name = u.getName();
    }

    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name="increment", strategy = "increment")
    @Column(name="id")
    public Long getId(){
        return id;
    }

    @Column(name = "username", unique = true)
    public String getName() {
        return name;
    }

    @Column(name = "password")
    public String getPass(){
        return pass;
    }

    public void setId(Long i){
        id = i;
    }

    public void setName(String n){
        name = n;
    }

    public void setPass(String p){
        pass = p;
    }
}

我想通过用户名在这个表中选择,在SQL smth中像这样select * from users where username = "abc";,但我怎么能用hibernate做呢?

5 个答案:

答案 0 :(得分:1)

这样做

Query query = getSession().createQuery("from user where name =:name ")
            .setParameter("name ", "abc");

名为abc的单个用户

 user u = (user) query.uniqueResult();

所有名称为abc

的用户
 List list = query.list();

答案 1 :(得分:0)

您可以在HQL中编写一个如下所示的查询:

Query query = session.createQuery("from user where name = :name");
query.setParameter("name", "abc");
List list = query.list(); // List of users
user usr = (user) query.uniqueResult(); // Single user

答案 2 :(得分:0)

  Query query=session.createQuery("FROM users where name=:name");
  query.setParameter("name","abc");
   List list=query.list();

答案 3 :(得分:0)

你可以使用类似的东西

  public user getUser(String username) {
    Session session = SessionUtil.sessionFactory.getCurrentSession();
    Transaction tx = session.beginTransaction();
    Query query = session.createQuery("From user where name=:name");
            query.setString("name", username);
            user result = (user) query.uniqueResult();
    tx.commit();
    return result;
}

如果您想使用模式,那么您可以使用以下内容:

    Query query = session.createQuery("From user where name like :name");
    query.setString("name", username);
    List result = query.list();

上面将使用模式,并返回具有匹配用户名模式的用户列表。

答案 4 :(得分:0)

 Session session = HibernateUtil.getSessionFactory().openSession();

        Query query = session.createQuery("from users where username = :name ");
        query.setParameter("name", "abc");

        // You can replace the above to commands with this one
        // Query query = session.createQuery("from Student where studentId = 1 ");
        List<?> list = query.list();

        User user = (User)list.get(0);

通过这种方式,你可以轻松地了解你想要的任何表格。