1. 程式人生 > >Hibernate配置及三種Id生成策略

Hibernate配置及三種Id生成策略

   hibernate的學習主要有:

    1.Id的生成策略

    2.表的關聯關係

    3.增刪改查

    4.優化

1.再說hibernate的Id生成策略之前,我們先來說一說hibernate的配置。

hibernate的配置預設的檔名為hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/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/studentManage</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        
        <property name="connection.useUnicode">true</property> 
        <property name="connection.characterEncoding">UTF-8</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect 資料庫方言-->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout是否打印出sql語句 -->
         <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup是否覆蓋舊錶,新建新表 -->
         <!--<property name="hbm2ddl.auto">create</property>--> 

        <!-- <mapping resource="com/hibernate/Teacher.hbm.xml"/>將實體與資料庫的表建立對應 -->
        <mapping class="com.SM.table.UserLogin"></mapping>
        <mapping class="com.SM.table.AcademyTable"></mapping>
        <mapping class="com.SM.table.ClassTable"></mapping>
        <mapping class="com.SM.table.StudentTable"></mapping>
        <mapping class="com.SM.table.CourseTable"></mapping>
        <mapping class="com.SM.table.GradeTable"></mapping>
    </session-factory>
</hibernate-configuration>


2.Id生成策略

2.1 預設的Id生成策略

@Entity
public class Customer {

@Id 
@GeneratedValue
Integer getId() { ... };
}
@Entity
public class Invoice {

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY)
Integer getId() { ... };
}

2.2 採用sequence的生成策略

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="SEQ_GEN")
@javax.persistence.SequenceGenerator(name="SEQ_GEN",sequenceName="my_sequence",allocationSize=20)
public Integer getId() { ... }

2.3 uuid的生成策略

@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
public String getId() {

以上的三種Id生成策略已經夠用....