JAVA web Hibernate HQL檢索練習-01
1.配置hibernate:
1)新增lib包
hibernate3.jar核心包,required下的jar包,jpa下的jar包,log4j包,self4j包,以及mysql的jar包
2)編寫實體類:Customer.java
public class Customer {
private Integer id;
private String name;
private Integer age;
private String sex;
private String city;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String toString(){
return "Customer:"+id+" "+name+" "+age+" "+sex+" "+city;
}
}
3)配置Customer.hbm.xml檔案
<hibernate-mapping>
<class name="book.c10.domain.Customer" table="customer">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" type="string" />
<property name="age" column="age" type="integer" />
<property name="sex" column="sex" type="string" />
<property name="city" column="city" type="string" />
</class>
</hibernate-mapping>
4)配置hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="book/c10/domain/Customer.hbm.xml" />
</session-factory>
</hibernate-configuration>
2.編寫練習類:
public class HQLtest {
/*
* 使用別名查詢
* */
@Test
public void aliasTest(){
/*
* 獲取configuration,建造SessionFactory,開啟Session,最後開啟事務
* */
Configuration config= new Configuration().configure();
SessionFactory sessionFactory=config.buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction t=session.beginTransaction();
/*
* 編寫hql,從session獲取query並放入hql,執行並獲取結果
* */
String hql="from Customer as c where c.name='Jack'";
Query query=session.createQuery(hql);
List<Customer> cs =query.list();
for(Customer c : cs){
System.out.println(c);
}
/*
* 提交事務,關閉session,關閉sessionFactory
* */
t.commit();
session.close();
sessionFactory.close();
}
}
3.編寫相關表,customer表
create database hibernate;
create table customer(
id int(11) not null AUTO_INCREMENT COMMENT '主鍵 id',
name VARCHAR(20) DEFAULT NULL COMMENT '姓名',
age INT(11) DEFAULT NULL COMMENT '年齡',
sex VARCHAR(2) DEFAULT NULL COMMENT '性別',
city VARCHAR(20) DEFAULT NULL COMMENT '城市',
PRIMARY KEY(id)
);
insert into customer (name,age,sex,city) values('Jack',16,'男','北京');
最後,使用JUnit4進行測試,結果:
出現問題:Mysql中文顯示問題(待解決)。