Reputation: 2062
i have such structure
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;
}
}
i want to select from this table by username, in SQL smth like this select * from users where username = "abc";
, but how i can do it with hibernate?
Upvotes: 1
Views: 3982
Reputation: 2279
you can use something like that
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;
}
if you want to use pattern then you can use something like below:
Query query = session.createQuery("From user where name like :name");
query.setString("name", username);
List result = query.list();
Above will use the pattern, and return list of users with matching username pattern.
Upvotes: 1
Reputation: 38
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);
with this you can easily get idea what you want with any table.
Upvotes: 0
Reputation: 786
Query query=session.createQuery("FROM users where name=:name");
query.setParameter("name","abc");
List list=query.list();
Upvotes: 0
Reputation: 45060
You can write a query in HQL which looks like this:
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
Upvotes: 0
Reputation: 26094
Do like this
Query query = getSession().createQuery("from user where name =:name ")
.setParameter("name ", "abc");
Single user with name abc
user u = (user) query.uniqueResult();
All users with name abc
List list = query.list();
Upvotes: 2