1. 程式人生 > >Hibernate 註解的方式進行查詢

Hibernate 註解的方式進行查詢

Student 類

@Entity
@NamedQueries(value={
        **@NamedQuery**(name="first",query="from Student"),
        **@NamedQuery**(name="second",query="from Student where name=:name")
})
@Table(name="t_student")
public class Student extends BaseEntity {

    private String name;
    private String sex;
    private
int age; private String email; public Student() { super(); // TODO Auto-generated constructor stub } public Student(int id) { super(id); // TODO Auto-generated constructor stub } public Student(String name, String sex, int age, String email) { this
.name = name; this.sex = sex; this.age = age; this.email = email; } @Override public String toString() { return "Student [id=" + id + ",name=" + name + ", sex=" + sex + ", age=" + age + ", email=" + email + "]"; } public String getName
() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Student(int id, String name, String sex, int age, String email) { super(id); this.name = name; this.sex = sex; this.age = age; this.email = email; } }

測試類

public class HQLDemo07 {

    public static void main(String[] args) {

        query();

    }


    /**
     * 演示HQL的使用
     * select  * from t_student where email='[email protected]' or '1'='1' and sex='女'
     */
    private static void query() {
        Session session=HibernateUtils.getSession();

        //List<Student> students=session.getNamedQuery("first").list();
        List<Student> students=**session.getNamedQuery**("second").setString("name", "童薇學生").list();
        System.out.println(students);



    }

}