hibernate配置
导入hibernate的jar包
编写hibernate配置文件
1234567891011121314151617181920<?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>
<!-- 数据库的方言,每个数据库都有自己的方言 -->
<property name=
"dialect"
>org.hibernate.dialect.MySQLDialect</property>
<property name=
"connection.url"
>jdbc:mysql:
//127.0.0.1:3306/hibernate</property>
<property name=
"connection.username"
>root</property>
<property name=
"connection.password"
></property>
<property name=
"connection.driver_class"
>com.mysql.jdbc.Driver</property>
<!-- 是否在控制台输出对应的sql语句 -->
<property name=
"show_sql"
>
true
</property>
<!-- 数据库更新方案,update是更新,还有覆盖之类的东西,用到时候去查找 -->
<property name=
"hbm2ddl.auto"
>update</property>
<!-- 加载映射文件 -->
<mapping resource=
"com/firefly/hibernate/domain/First.hbm.xml"
/>
</session-factory>
</hibernate-configuration>
编写实体类,并未实体类加载映射文件,记得倒回去修改配置文件中的加载映射文件语句。
编写java文件对数据库进行操作
1234567891011121314151617181920212223242526272829303132package
com.firefly.hibernate.hibernate;
import
org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.Transaction;
import
org.hibernate.cfg.Configuration;
import
com.firefly.hibernate.domain.First;
public
class
News {
public
static
void
main(
String
[] args) throws Exception {
//获得configuration对象
Configuration conf =
new
Configuration().configure();
//创建session工厂
SessionFactory sf = conf.buildSessionFactory();
//打开session
Session sess = sf.openSession();
//开始事务
Transaction tx =sess.beginTransaction();
First f =
new
First();
f.setId(
1
);
f.setTitle(
"我是第一条数据!"
);
f.setContent(
"I'm content"
);
sess.save(f);
//提交事务
tx.commit();
//关闭session
sess.close();
//关闭session工厂
sf.close();
}
}
以上是向数据库中添加一条数据
关于hibernate运行流程:
hibernate的思想是将对关系型数据库的操作改变为符合java面向对象编程思想的操作。
hibernate将数据库中的数据映射成为对象通过与实体类对应的映射文件实现;而对对象的操作是放在session容器中的,而session对象的获取是通过session工厂生产的,session工厂是通过configuration对象的来的,在获得configuration对象过程中关联了相关的实体类映射文件。