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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Hibernate 第一个体验程序

發布時間:2023/12/10 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Hibernate 第一个体验程序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先要導入包,將下載的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"

/>

轉載于:https://www.cnblogs.com/flying607/p/3474223.html

總結

以上是生活随笔為你收集整理的Hibernate 第一个体验程序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。