日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Hibernate 第一个体验程序

發(fā)布時(shí)間:2023/12/10 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Hibernate 第一个体验程序 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

首先要導(dǎo)入包,將下載的hibernate所有required包導(dǎo)入,將下載的hibernate用來(lái)寫(xiě)log的slf4j的api和nopjar包導(dǎo)入,將下載的mysql鏈接引擎jar包導(dǎo)入。

?

然后新建java工程。

?

先告訴hiernate怎么連數(shù)據(jù)庫(kù):在hibernate默認(rèn)識(shí)別目錄src根目錄下以默認(rèn)hibernate配置文件名hibernate.cfg.xml建立xml(都采用默認(rèn)可以省去在代碼中書(shū)寫(xiě)路徑和名字的麻煩):

?

<?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ù)庫(kù)連接池大小?-->

??????? <!-- SQL dialect sql語(yǔ)句方言-->
??????? <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ù)的時(shí)候要用該值),custom.class(自定義class管理currentSession)

      jta:java transaction api,java中一種用于管理事務(wù)的api,和實(shí)現(xiàn)了該api的應(yīng)用服務(wù)器的JTATransactionManager結(jié)合使用可以處理分布存儲(chǔ)。

?


-->
??????? <!-- 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ù)庫(kù)和model的映射關(guān)系,也采用默認(rèn)目錄和命名方式:

在model(這里是Student類)所在目錄下新建Student.hbm.xml,名字要和類名一致,對(duì)于Teacher類,因?yàn)槭褂昧俗⒔馑圆恍枰?#xff0c;也可以看出來(lái)使用注解相對(duì)來(lái)說(shuō)比較方便。

?

配置文件中如果表名和類名不一致也可以指定表名,參見(jiàn)本文末尾處的一段配置

?

<?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ù)庫(kù)也一致,只有三列,其中id是主鍵。

指定id生成策略示例代碼:

<id name="id">

???? <generator class="uuid"></generator>

<!-- 指定數(shù)據(jù)庫(kù)該主鍵生成策略為uuid,uuid要求主鍵必須是個(gè)字符串才能采用,uuid全局唯一id。指定生成策略后就不需要手動(dòng)設(shè)置主鍵了。

還可以設(shè)成:native,int型,會(huì)根據(jù)數(shù)據(jù)庫(kù)本地自動(dòng)生成。

關(guān)于生成策略更多內(nèi)容參見(jiàn)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ù)庫(kù)內(nèi)容一一對(duì)應(yīng),無(wú)需額外書(shū)寫(xiě)映射關(guān)系xml
//@Table(name = “_Teacher”) 如果表名和類名不一致(不區(qū)分大小寫(xiě)),可以用這個(gè)注解來(lái)標(biāo)明表名

public class Teacher {
??? private int id;
??? private String name;
??? private String title;

??? private Date birthDate;
????
??? @Id? //主鍵

??? //@Basic //對(duì)于和數(shù)據(jù)對(duì)應(yīng)的字段可以寫(xiě),相當(dāng)于加了

??? public int getId() {
??????? return id;
??? }


??? public void setId(int id) {
??????? this.id = id;
??? }

?@Column(name=”_name”)//字段名和屬性名不對(duì)應(yīng)時(shí)可以這樣指定對(duì)應(yīng)的屬性名
??? public String getName() {
??????? return name;
??? }
??? public void setName(String name) {
??????? this.name = name;
??? }

//如果不想往數(shù)據(jù)庫(kù)中存放,可以加個(gè)注解,透明的—@Transient

??? public String getTitle() {
??????? return title;
??? }
??? public void setTitle(String title) {
??????? this.title = title;
??? }

?

//可以只保存錄入時(shí)間的日期部分或者時(shí)間部分@Temporal(TemporalType.DATE),這樣數(shù)據(jù)庫(kù)中就會(huì)用DATE類型來(lái)保存數(shù)據(jù),默認(rèn)是DATETIME,日期時(shí)間一起保存

??? public Date getBirthDate(){

??????? return birthDate;

??? }

??? public void setBirthDate(Date birthDate){

??????? this.birthDate=birthDate;

??? }
}

?

?

關(guān)于用注解的方式指定主鍵生成策略:

@GeneratedValue? 默認(rèn)策略AUTO,相當(dāng)于xml中的native,會(huì)使數(shù)據(jù)庫(kù)根據(jù)本地策略自動(dòng)生成,如果是mysql會(huì)auto increament,如果是oracle則sequence。

@GeneratedValue(strategy = GenerationType.IDENTITY)

@GeneratedValue(strategy = GenerationType.SEQUENCE)

?

@SequenceGenerator(name="thissequencegeneratorname",sequenceName="aa")定義一個(gè)generator前者是它自己的名字,后者是它采用的數(shù)據(jù)庫(kù)中的生成器的名字,定義要寫(xiě)在@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ù)庫(kù)平臺(tái)

?@Id
?@GeneratedValue(strategy=GenerationType.TABLE, generator="Teacher_GEN")
?public int getId() {
??return id;
?}

?

?

?

?

然后就可以寫(xiě)測(cè)試類了:

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ù)就會(huì)去找默認(rèn)目錄下的xml
??????? ServiceRegistry? sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
??????? SessionFactory sf = cfg.buildSessionFactory(sr);//生成session工廠,相當(dāng)于產(chǎn)生數(shù)據(jù)庫(kù)連connection的工廠
???????
??????? Session session = sf.openSession();//相當(dāng)于數(shù)據(jù)庫(kù)的一個(gè)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;過(guò)時(shí)了,該類的所有內(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("中級(jí)");
???????
??????? //Configuration cfg = new AnnotationConfiguration();
??????? Configuration cfg = new Configuration();
???????
??????? //SessionFactory sf = cfg.configure().buildSessionFactory();
???????
??????? cfg.configure();//解析所有hibernate的配置xml,不指定參數(shù)就會(huì)去找默認(rèn)目錄下的xml
??????? ServiceRegistry? sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
??????? SessionFactory sf = cfg.buildSessionFactory(sr);//生成session工廠,相當(dāng)于產(chǎn)生數(shù)據(jù)庫(kù)連connection的工廠
???????
??????? Session session = sf.openSession();//相當(dāng)于數(shù)據(jù)庫(kù)的一個(gè)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 第一个体验程序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。