Hibernate 第一个体验程序
首先要導(dǎo)入包,將下載的hibernate所有required包導(dǎo)入,將下載的hibernate用來寫log的slf4j的api和nopjar包導(dǎo)入,將下載的mysql鏈接引擎jar包導(dǎo)入。
?
然后新建java工程。
?
先告訴hiernate怎么連數(shù)據(jù)庫:在hibernate默認(rèn)識別目錄src根目錄下以默認(rèn)hibernate配置文件名hibernate.cfg.xml建立xml(都采用默認(rèn)可以省去在代碼中書寫路徑和名字的麻煩):
?
<?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>?數(shù)據(jù)庫連接池大小?-->
??????? <!-- 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(當(dāng)前線程),jta,managed(jee、EJB中使用applicationserver,且要手工管理currentSession手工管理事務(wù)的時候要用該值),custom.class(自定義class管理currentSession)
jta:java transaction api,java中一種用于管理事務(wù)的api,和實(shí)現(xiàn)了該api的應(yīng)用服務(wù)器的JTATransactionManager結(jié)合使用可以處理分布存儲。
?
-->
??????? <!-- 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數(shù)據(jù)庫和model的映射關(guān)系,也采用默認(rèn)目錄和命名方式:
在model(這里是Student類)所在目錄下新建Student.hbm.xml,名字要和類名一致,對于Teacher類,因?yàn)槭褂昧俗⒔馑圆恍枰?#xff0c;也可以看出來使用注解相對來說比較方便。
?
配置文件中如果表名和類名不一致也可以指定表名,參見本文末尾處的一段配置
?
<?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>
?
數(shù)據(jù)庫也一致,只有三列,其中id是主鍵。
指定id生成策略示例代碼:
<id name="id">
???? <generator class="uuid"></generator>
<!-- 指定數(shù)據(jù)庫該主鍵生成策略為uuid,uuid要求主鍵必須是個字符串才能采用,uuid全局唯一id。指定生成策略后就不需要手動設(shè)置主鍵了。
還可以設(shè)成:native,int型,會根據(jù)數(shù)據(jù)庫本地自動生成。
關(guān)于生成策略更多內(nèi)容參見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?? //實(shí)體類 表示和數(shù)據(jù)庫內(nèi)容一一對應(yīng),無需額外書寫映射關(guān)系xml
//@Table(name = “_Teacher”) 如果表名和類名不一致(不區(qū)分大小寫),可以用這個注解來標(biāo)明表名
public class Teacher {
??? private int id;
??? private String name;
??? private String title;
??? private Date birthDate;
????
??? @Id? //主鍵
??? //@Basic //對于和數(shù)據(jù)對應(yīng)的字段可以寫,相當(dāng)于加了
??? public int getId() {
??????? return id;
??? }
??? public void setId(int id) {
??????? this.id = id;
??? }
?@Column(name=”_name”)//字段名和屬性名不對應(yīng)時可以這樣指定對應(yīng)的屬性名
??? public String getName() {
??????? return name;
??? }
??? public void setName(String name) {
??????? this.name = name;
??? }
//如果不想往數(shù)據(jù)庫中存放,可以加個注解,透明的—@Transient
??? public String getTitle() {
??????? return title;
??? }
??? public void setTitle(String title) {
??????? this.title = title;
??? }
?
//可以只保存錄入時間的日期部分或者時間部分@Temporal(TemporalType.DATE),這樣數(shù)據(jù)庫中就會用DATE類型來保存數(shù)據(jù),默認(rèn)是DATETIME,日期時間一起保存
??? public Date getBirthDate(){
??????? return birthDate;
??? }
??? public void setBirthDate(Date birthDate){
??????? this.birthDate=birthDate;
??? }
}
?
?
關(guān)于用注解的方式指定主鍵生成策略:
@GeneratedValue? 默認(rèn)策略AUTO,相當(dāng)于xml中的native,會使數(shù)據(jù)庫根據(jù)本地策略自動生成,如果是mysql會auto increament,如果是oracle則sequence。
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
?
@SequenceGenerator(name="thissequencegeneratorname",sequenceName="aa")定義一個generator前者是它自己的名字,后者是它采用的數(shù)據(jù)庫中的生成器的名字,定義要寫在@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
?)//表生成器,可以跨數(shù)據(jù)庫平臺
?@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,不指定參數(shù)就會去找默認(rèn)目錄下的xml
??????? ServiceRegistry? sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
??????? SessionFactory sf = cfg.buildSessionFactory(sr);//生成session工廠,相當(dāng)于產(chǎn)生數(shù)據(jù)庫連connection的工廠
???????
??????? Session session = sf.openSession();//相當(dāng)于數(shù)據(jù)庫的一個connection
??????? session.beginTransaction();
??????? //session.save(s);
??????? //session.delete(s);
??????? session.update(s);
??????? session.getTransaction().commit();
??????? session.close();//關(guān)閉connection
??????? sf.close();//關(guān)閉工廠相當(dāng)于關(guān)閉了數(shù)據(jù)連接池
??? }
}
?
?
import org.hibernate.Session;
import org.hibernate.SessionFactory;
//import org.hibernate.cfg.AnnotationConfiguration;過時了,該類的所有內(nèi)容都已經(jīng)被包含在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,不指定參數(shù)就會去找默認(rèn)目錄下的xml
??????? ServiceRegistry? sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
??????? SessionFactory sf = cfg.buildSessionFactory(sr);//生成session工廠,相當(dāng)于產(chǎn)生數(shù)據(jù)庫連connection的工廠
???????
??????? Session session = sf.openSession();//相當(dāng)于數(shù)據(jù)庫的一個connection
??????? session.beginTransaction();
??????? session.save(t);
??????? session.getTransaction().commit();
??????? session.close();//關(guān)閉connection
??????? sf.close();//關(guān)閉工廠相當(dāng)于關(guān)閉了數(shù)據(jù)連接池
??? }
}
?
?
?
?
?
?
?
?
?
?
?
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"
/>
轉(zhuǎn)載于:https://www.cnblogs.com/flying607/p/3474223.html
總結(jié)
以上是生活随笔為你收集整理的Hibernate 第一个体验程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Com组件介绍
- 下一篇: 私密智能搜题小助手,支持智能图片识别和智