2014-03-03 71 views
1

我有這樣的結構通過現場選擇休眠

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水木清華這樣select * from users where username = "abc";,但我怎麼能與Hibernate做呢?

回答

1

做這樣

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

與名爲abc單用戶

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

與名爲abc的所有用戶

List list = query.list(); 
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 
0
Query query=session.createQuery("FROM users where name=:name"); 
    query.setParameter("name","abc"); 
    List list=query.list(); 
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(); 

以上將使用該模式,並返回列表用戶名匹配的用戶模式。

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); 

用這個,你可以很容易地知道你想要什麼表。