1.下载hibernate jar包 在lib目录下require目录下的jar文件。
新建一个Dynamic项目。
1)创建一个Hibernate配置文件
文件名字为:hibernate.cfg.xml 并且该文件放置于src根目录下
内容为
<?xml version='1.0' encoding='UTF-8'?>
<!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.username">root</property>
<property name="connection.password">wdl03707552882</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///localhost:3306/test</property>
<!-- 配置hibernate的基本信息 -->
<!-- hibernate所使用的数据库方言 -->
<property name="dialect">#hibernate.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>
<!-- 指定关联的.hbm.xml文件 -->
<mapping resource="com/hibernate/test/News.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2)创建一个持久化类。建立在当前web项目的某个包下实现getter settter tostring 等方法。
内容如下
3)创建对象关系映射文件package com.hibernate.test; import java.util.Date; public class News { private Integer id; private String title; private String author; private Date date; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public News(Integer id, String title, String author, Date date) { super(); this.id = id; this.title = title; this.author = author; this.date = date; } public News() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "News [id=" + id + ", title=" + title + ", author=" + author + ", date=" + date + "]"; } }
文件放置于当前持久化类的包下 文件名字和持久化类名字相同 扩展名为.hbm.xml
具体格式如下:
<?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> <class name="com.hibernate.test.News" table="xs"> <id name="id" type="java.lang.Integer"> <column name="ID"></column> <!--指定主键的生成方式 native:使用数据库本地方式 --> <generator class="native"></generator> </id> <property name="title" type="java.lang.String"> <column name="TITLE"></column> </property> <property name="data"> <column name="AUTHOR"></column> </property> <property name="author" type="java.lang.String"> <column name="AUTHOR"></column> </property> </class> </hibernate-mapping>
4)通过hibernateapi编写访问数据库代码