1. 向lib中导入jar包:
slf4j-api-1.6.1.jar、mysql-connector-java-5.1.5-bin.jar、jta-1.1.jar、javassist-3.12.0.GA.jar、hibernate3.jar、dom4j-1.6.1.jar、antlr-2.7.6.jar 、
hibernate-jpa-2.0-api-1.0.0.Final.jar、commons-collections-3.1.jar
并将这些jar包应用到Referenced Libraries中。
2. 在根目录下建立hibernate.cfg.xml文件并配置信息:
<!-- 配置数据库信息 -->
<property name="dialect">//配置方言
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">//配置url
jdbc:mysql://localhost:3306/hibernate
</property>
<property name="connection.driver_class">//配置JDBC驱动
com.mysql.jdbc.Driver
</property>
<property name="connection.username">root</property>//用户名
<property name="connection.password">mysqldbms</property>//密码
<!-- 显示生成的SQL语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 导入映射文件 -->
<mapping resource="it/cast/User.hbm.xml" />
3. 在java类的包下建立User.hbm.xml文件并配置:
<class name="JavaClassName" table="tableName">
<!-- id元素用于映射主键 -->
<id name="id" type="int" column="id">
<!-- native:使用数据库的自动增长策略 -->
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
</class>
4. 在User类中建两个属性id和name,并建立起get和set方法:
public class User {
private Integer id;
private String name;
// 属性为集合类型,生命并实例化,实例化后,在其它类中就可以直接调用了
private Set<String> addressSet = new HashSet<String>();
public Integer getId() {
return id;
}
public Set<String> getAddressSet() {
return addressSet;
}
public void setAddressSet(Set<String> addressSet) {
this.addressSet = addressSet;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 重写toString函数
public String toString() {
return "User [id=" + id + ", name=" + name + ", addressSet="
+ addressSet + "]";
}
}
5.
封装一个专门生成
session
的类:
/**
* 用来生成session的封装类
* @author A_shun
*/
public class HibernateUtils {
// SessionFactory全局只需要一个
private static SessionFactory sessionFactory;
//session全局只需一个
private static Session session = null;
static {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");// 读取指定地址的文件
//建立sessionFactory工厂
sessionFactory = cfg.buildSessionFactory();
session = sessionFactory.openSession();//开启一个session
}
/**
* 获取全局唯一的session
*/
public static Session getSession() {
return session;
}
}
6. 新建持久化层类,其中代码如下:
@Test
// 保存属性的方法
public void testSave() throws Exception {
User user = new User();
user.setName("zhangSan");
// 打开一个新的Session
Session session = sessionFactory.openSession();
// 开始事务
Transaction tx = (Transaction) session.beginTransaction();
session.save(user);//保存对象
tx.commit();// 提交事务
session.close();// 释放Session占用的内存
}
@Test
// 获取属性的方法
public void testGet() {
// 打开一个新的Session
Session session = sessionFactory.openSession();
// 开始事务
Transaction tx = (Transaction) session.beginTransaction();
//取得user对象的第一个属性
User user = (User) session.get(User.class, 1);
System.out.println(user);//输出user对象
tx.commit();//提交事务
session.close();//释放session占用的内存
}