- 下载hibernate开发包:
在本章之前需要继承hibernate开发插件到eclipse,详细操作请参考我的博文:《Hibernate(一):安装hibernate插件到eclipse环境》
官网地址:http://hibernate.org/
下载页面:
下载的版本是Hibernate5.2.9(hibernate-release-5.2.9.Final.zip)
解压下载的开发包。
- 新建HelloWorld工程:
在eclipse新建project工程,工程名:Hibernate_01
在工程根目录下新建一个lib文件夹,hibernate-release-5.2.9.Final.zip解压目录是:D:\Work\Java\hibernate-release-5.2.9.Final,把D:\Work\Java\hibernate-release-5.2.9.Final\lib\required下的所有jar包拷贝到工程新建的lib文件夹下。
找到mysql的开发包,并拷贝到lib文件夹下。
选中lib文件夹下的所有jar包,右键菜单-》Build Path->Add to Build Path。
新建hibernate.cfg.xml文件
<?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="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_01</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="com/dx/hibernate5/test/News.hbm.xml" /> <mapping class="com.dx.hibernate5.test.News" /> </session-factory> </hibernate-configuration>
备注:关于"hibernate.hbm2ddl.auto"可选项包括:update|create| create-drop |validate
--create:会根据.hbm.xml文件来生成数据表,但是每次运行都会删除上一次的表,重新生成表,那怕二次没有任何改变。
--create-drop:会根据.hbm.xml文件来生成数据表,但是SessionFactory一旦关闭,表就被自动删除。
--update:(最常用的一种配置选择,)会根据.hbm.xml文件来生成数据表,但如果.hbm.xml文件和数据库中对应的数据表的表结构不同,Hibernate将更新数据表结构,但不会删除已有的行和列。
--validate:会和数据库中的表进行比较,若.hbm.xml文件中的列在数据表中不存在,则会抛出异常。
新建News.java
package com.dx.hibernate5.test; import java.util.Date; public class News { private Integer id; private String author; private String content; private Date createDate; public News() { } public News(String author, String content, Date createDate) { super(); this.author = author; this.content = content; this.createDate = createDate; } public News(Integer id, String author, String content, Date createDate) { super(); this.id = id; this.author = author; this.content = content; this.createDate = createDate; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @Override public String toString() { return "News [>; } }