Hibernate 开发步骤:
1. 创建持久化类
package com.huawei.hibernate;
public class News {
private Integer id;
private String title;
private String content;
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "News [id=" + id + ", title=" + title + ", content=" + content + "]";
}
}
2. 创建对象-关系映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.huawei.hibernate">
<class name="News" table="NEWS_TABLE">
<id name="id" column="NEWS_ID">
<generator class="native"></generator>
</id>
<property name="title" column="TITLE"></property>
<property name="content" column="CONTENT"></property>
</class>
</hibernate-mapping>
3.创建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 节点 -->
<session-factory>
<!-- 连接数据库的基本信息: user, password, url, driverClass -->
<property name="connection.username">root</property>
<property name="connection.password">nssol001</property>
<property name="connection.url">jdbc:mysql:///hibernate</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 配置数据库方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 在进行数据库相关操作时, 是否在控制台打印 SQL 代码 -->
<property name="show_sql">true</property>
<!-- 配置是否自动生成数据表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 关联 Hibernate 映射文件 -->
<mapping resource="com/huawei/hibernate/News.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4.通过Hibernate API 编写访问数据库的代码
package com.huawei.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
Configuration configeration = new Configuration().configure();
SessionFactory factory = configeration.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
News news = new News();
news.setTitle("hibernate");
news.setContent("ORM");
session.save(news);
tx.commit();
session.close();
factory.close();
}
}