1 引入相关的jar包
* hibernate的相关jar包
hibernate-distribution-3.5.6-Final\lib\required\*.jar
hibernate3.jar
hibernate-annotations-3.4.0.GA\lib\test\slf4j-log4j12.jar
hibernate-annotations-3.4.0.GA\lib\test\log4j.jar
* junit测试的jar包
junit-4.8.2.jar
* mysql的驱动jar包
mysql-connector-java-5.1.10-bin.jar
2 创建表和对应的javaBean文件(持久化类) 该映射文件的规范在org.hibernate. hibernate-mapping-3.0.dtd文件中
3 类名.hbm.xml 与实体类是同一级目录
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.yue.domain">
<class name="User" table="users">
<id name="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"></property>
<property name="password" column="password" type="string"></property>
</class>
</hibernate-mapping>
4 hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/yue
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">yue4512138</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
5 加载xml
private static SessionFactory sf = null;
static {
// 实例化配置对像
Configuration configuration = new Configuration();
// 直接从类路径下加载hibernate.cfg.xml
configuration.configure();
//方法二:从同包下加载
//configuration.configure("cn/yue/domain/hibernate.cfg.xml");
// 加载user.hbm.xml
configuration.addClass(User.class);
// 方法二:
//configuration.addResource("cn/yue/domain/User.hbm.xml");
// 获取session工厂
sf = configuration.buildSessionFactory();
}
6 保存
@Test
public void saveUser()
{
//开启session
//sf.getCurrentSession();
Session session=sf.openSession();
//开启事物
Transaction transaction=session.beginTransaction();
//创建对像
User user=new User();
user.setName("yue");
user.setPassword("123");
//保存对像
session.save(user);
//提交事物
transaction.commit();
//关闭session
session.close();
}
hibernate学习笔记一
最新推荐文章于 2024-08-25 21:18:14 发布