For refrence l开发者_如何学编程ook http://singgihpraditya.wordpress.com/2010/02/13/spring-3-0-and-hibernate-tutorial-part-1/
@Entity
@Table(name="USER")
public class User implements Serializable {
private Long id;
private String name;
private String password;
@Id
@GeneratedValue
@Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private HibernateTemplate hibernateTemplate;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
the above part is code from 2 files , just to give you some code as people here like to ask for it
the important part:
@Override
public User getUser(Long id) {
return hibernateTemplate.get(User.class, id);
}
As we can see get User by his ID is easy..
I want to : i'm sure its easy I just dont know how , and I know there is the alternative way to get all User into a a List<User>
and serach with for(..)
but I don't want that way, I want the elegant way.
* return user by name
* return true/false if user exists by name
You need queries to search for entities. Read the user guide about queries. The same page also contains a whole section about HQL, the query language used to write queries.
It's something like this, more and less:
String sqlQuery =" from User
as user where user.name=:name";
Query query = session.createQuery
(SQL_QUERY);
query.setString("name",name);
List<User> = query.list();
For more information see this chapter
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#queryhql
精彩评论