hibernate环境配置一共分为三个步骤:
1.导入第三方jar包(包括数据库的驱动)
\hibernate-release-4.2.3.Final\lib\required目录下 所有jar包还需要一个MySQL的驱动包:
2.配置.cfg.xml文件
创建一个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>
<!--hibernate链接数据库的基本信息 -->
<property name="connection.username">root</property>
<property name="connection.password">tiger</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///test</property>
<!--hibernate的基本配置 -->
<!--hibernate使用的数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- 运行时是否打印sql -->
<property name="show_sql">true</property>
<!-- 运行时是否格式化sql -->
<property name="format_sql">true</property>
<!-- 生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property>
<!-- 需要关联的hibernate映射文件.hbm.xml -->
<mapping resource="cn/com/News.hbm.xml"/>
</session-factory>
</hibernate-configuration>
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">
<!-- Generated 2015-7-28 10:36:31 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="cn.com.News" table="NEWS">
<id name="id" type="java.lang.Integer" access="field">
<column name="ID" />
<generator class="native" />
</id>
<property name="title" type="java.lang.String">
<column name="TITLE" />
</property>
<property name="author" type="java.lang.String">
<column name="AUTHOR" />
</property>
<property name="date" type="java.util.Date">
<column name="DATE" />
</property>
</class>
</hibernate-mapping>
测试:
public class Test {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
@After
public void destory() {
transaction.commit();
session.close();
sessionFactory.close();
}
@org.junit.Test
public void test() {
News news = (News) session.get(News.class, 1);
System.out.println(news);
}
}