hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接设置 -->
<property name="connection.driver_class">数据库驱动</property>
<property name="connection.url">连接数据库的url</property>
<property name="connection.username">数据库账号</property>
<property name="connection.password">数据库密码</property>
<!-- 设置方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 查看sql语句和格式化 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 自动创建数据库表
create:删除旧表在创建新表
-->
<property name="hbm2ddl.auto">update</property>
<mapping resource="实体映射路径/实体首字母大写.hbm.xml" />
<!--
注解方式 实体类,类名上加@Entity @Id加在get方法上
<mapping class="全类名"/>
-->
</session-factory>
</hibernate-configuration>
实体首字母大写.hbm.xml放置在vo包下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="要映射的包名">
<class name="类名,不写映射的包名就要写全类名" table="这个类对应的那个数据库表名">
<!-- 如果column不写默认name值 -->
<id name="id" column="表字段">
<generator class="increment"/>
</id>
<property name="类的成员变量" type="string|integer|timestamp" column="表字段"/>
</class>
</hibernate-mapping>
java
//获得Session工厂,hibernate3之前
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
/*
注解方式
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
*/
//获得session
Session session = sessionFactory.openSession();
//开启事务
session.beginTransaction();
session.save(Object);
List result = session.createQuery("from 数据库表名").list();
for (实体名 实体名引用 : (List<实体名>) result) {
//遍历
}
//提交
session.getTransaction().commit();
//关闭连接
session.close();
if (sessionFactory != null) {
sessionFactory.close();
}