首先要匯入包,將下載的hibernate所有required包匯入,將下載的hibernate用來寫log的slf4j的api和nopjar包匯入,將下載的mysql連結引擎jar包匯入。
然後新建java工程。
先告訴hiernate怎麼連資料庫:在hibernate預設識別目錄src根目錄下以預設hibernate配置檔名hibernate.cfg.xml建立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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<!--
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
-->
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> 資料庫連線池大小 -->
<!-- SQL dialect sql語句方言-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property>
指定getCurrentSession的上下文,如果不指定只能用openSession。有thread(當前執行緒),jta,managed(jee、EJB中使用applicationserver,且要手工管理currentSession手工管理事務的時候要用該值),custom.class(自定義class管理currentSession)
jta:java transaction api,java中一種用於管理事務的api,和實現了該api的應用伺服器的JTATransactionManager結合使用可以處理分佈儲存。
-->
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format _sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">update</property>
-->
<mapping resource="com/test/hibernate/model/Student.hbm.xml"/>
<mapping class="com.test.hibernate.model.Teacher"/>
</session-factory>
</hibernate-configuration>
然後告訴hibernate資料庫和model的對映關係,也採用預設目錄和命名方式:
在model(這裡是Student類)所在目錄下新建Student.hbm.xml,名字要和類名一致,對於Teacher類,因為使用了註解所以不需要,也可以看出來使用註解相對來說比較方便。
配置檔案中如果表名和類名不一致也可以指定表名,參見本文末尾處的一段配置
<?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.test.hibernate.model">
<class name="Student">
<id name="id"></id>
<property name="name"></property>
<property name="age"></property>
</class>
</hibernate-mapping>
資料庫也一致,只有三列,其中id是主鍵。
指定id生成策略示例程式碼:
<id name="id">
<generator class="uuid"></generator>
<!-- 指定資料庫該主鍵生成策略為uuid,uuid要求主鍵必須是個字串才能採用,uuid全域性唯一id。指定生成策略後就不需要手動設定主鍵了。
還可以設成:native,int型,會根據資料庫本地自動生成。
關於生成策略更多內容參見hibernate API "5.1.2.2.1. Various additional generators" -->
</id>
Student類:
package com.test.hibernate.model;
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Teacher類:
package com.test.hibernate.model;
import javax.persistence.*;
import java.util.Date;
@Entity //實體類 表示和資料庫內容一一對應,無需額外書寫對映關係xml
//@Table(name = “_Teacher”) 如果表名和類名不一致(不區分大小寫),可以用這個註解來標明表名
public class Teacher {
private int id;
private String name;
private String title;
private Date birthDate;
@Id //主鍵
//@Basic //對於和資料對應的欄位可以寫,相當於加了
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name=”_name”)//欄位名和屬性名不對應時可以這樣指定對應的屬性名
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//如果不想往資料庫中存放,可以加個註解,透明的—@Transient
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
//可以只儲存錄入時間的日期部分或者時間部分@Temporal(TemporalType.DATE),這樣資料庫中就會用DATE型別來儲存資料,預設是DATETIME,日期時間一起儲存
public Date getBirthDate(){
return birthDate;
}
public void setBirthDate(Date birthDate){
this.birthDate=birthDate;
}
}
關於用註解的方式指定主鍵生成策略:
@GeneratedValue 預設策略AUTO,相當於xml中的native,會使資料庫根據本地策略自動生成,如果是mysql會auto increament,如果是oracle則sequence。
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name="thissequencegeneratorname",sequenceName="aa")定義一個generator前者是它自己的名字,後者是它採用的資料庫中的生成器的名字,定義要寫在@Entity下面,類上面。下面這一行是採用該generator
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="thissequencegeneratorname")
@Entity
@javax.persistence.TableGenerator(
name="Teacher_GEN",
table="GENERATOR_TABLE",
pkColumnName = "pk_key",
valueColumnName = "pk_value",
pkColumnValue="Teacher",
allocationSize=1
)//表生成器,可以跨資料庫平臺
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="Teacher_GEN")
public int getId() {
return id;
}
然後就可以寫測試類了:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import com.test.hibernate.model.Student;
public class StudentTest {
public static void main(String args[]){
Student s = new Student();
s.setId(1);
s.setName("s2");
s.setAge(1);
Configuration cfg = new Configuration();
//SessionFactory sf = cfg.configure().buildSessionFactory();
cfg.configure();//解析所有hibernate的配置xml,不指定引數就會去找預設目錄下的xml
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);//生成session工廠,相當於產生資料庫連connection的工廠
Session session = sf.openSession();//相當於資料庫的一個connection
session.beginTransaction();
//session.save(s);
//session.delete(s);
session.update(s);
session.getTransaction().commit();
session.close();//關閉connection
sf.close();//關閉工廠相當於關閉了資料連線池
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
//import org.hibernate.cfg.AnnotationConfiguration;過時了,該類的所有內容都已經被包含在Configuration類中。
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import com.test.hibernate.model.Teacher;
public class TeacherTest {
public static void main(String args[]){
Teacher t = new Teacher();
t.setId(2);
t.setName("t3");
t.setTitle("中級");
//Configuration cfg = new AnnotationConfiguration();
Configuration cfg = new Configuration();
//SessionFactory sf = cfg.configure().buildSessionFactory();
cfg.configure();//解析所有hibernate的配置xml,不指定引數就會去找預設目錄下的xml
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sf = cfg.buildSessionFactory(sr);//生成session工廠,相當於產生資料庫連connection的工廠
Session session = sf.openSession();//相當於資料庫的一個connection
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();//關閉connection
sf.close();//關閉工廠相當於關閉了資料連線池
}
}
class配置參考例子:
<class
name="ClassName"
table="tableName"
discriminator-value="discriminator_value"
mutable="true|false"
schema="owner"
catalog="catalog"
proxy="ProxyInterface"
dynamic-update="true|false"
dynamic-insert="true|false"
select-before-update="true|false"
polymorphism="implicit|explicit"
where="arbitrary sql where condition"
persister="PersisterClass"
batch-size="N"
optimistic-lock="none|version|dirty|all"
lazy="true|false"
entity-name="EntityName"
check="arbitrary sql check condition"
rowid="rowid"
subselect="SQL expression"
abstract="true|false"
node="element-name"
/>