1. 程式人生 > >hibernate中設定欄位不持久化 註解

hibernate中設定欄位不持久化 註解

hibernate中Modle中的有些屬性不想建立表是在資料庫中產生欄位儲存資料,當這種需求是我們可以設定@transient表示透明的當設定此屬性是在建立資料庫是可以對此屬性忽略,在本例中模擬了一個班級表表名為MyClass 屬性有資料庫id 班級名稱 班級老師 老師身份證號 我們的需求想把老師身份證號不儲存到資料庫裡不想對身份證不持久化資料解決方法很簡單就是在對應的欄位上面加@Transient的註解就搞定。

例項程式碼如下:

第一步:建立Java工程編寫三個專案包把hibernate用的jar包新增到path裡然後建立Modle類程式碼如下

package com.ygc.hibernate.modle;  
  
import java.io.Serializable;  
  
import javax.persistence.Basic;  
import javax.persistence.Entity;  
import javax.persistence.GeneratedValue;  
import javax.persistence.GenerationType;  
import javax.persistence.Id;  
import javax.persistence.Table;  
import javax.persistence.Transient;  
@Entity  
@Table(name="Class")  //設定資料庫表名為class  
public class MyClass implements Serializable {  
    private int id;  
    private String className;  
    private String teacher;  
    private String teacherNumber;  
      
    @Id  
    @GeneratedValue(strategy=GenerationType.AUTO)  //設定主鍵自動增長  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
      
    @Basic  
    public String getClassName() {  
        return className;  
    }  
    public void setClassName(String className) {  
        this.className = className;  
    }  
    public String getTeacher() {  
        return teacher;  
    }  
    public void setTeacher(String teacher) {  
        this.teacher = teacher;  
    }  
    //這是此註解後該屬性不會資料持久化也是本例要說明的註解  
    @Transient  
    public String getTeacherNumber() {  
        return teacherNumber;  
    }  
    public void setTeacherNumber(String teacherNumber) {  
        this.teacherNumber = teacherNumber;  
    }  
}  

第二步:編寫測試類就是Main方法的。

package com.ygc.hibernate.main;  
import org.hibernate.Session;  
  
import com.ygc.hibernate.modle.MyClass;  
import com.ygc.hibernate.utils.HibernateUtils;  
public class ClassTest {  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        MyClass clas1 = new MyClass();  
        clas1.setClassName("大學二年級");  
        clas1.setTeacher("田紅菊");  
        clas1.setTeacherNumber("0100");  
          
        Session session = HibernateUtils.getFactory().openSession();  
        session.beginTransaction();  
        session.save(clas1);  
        session.getTransaction().commit();  
        session.close();  
        HibernateUtils.getFactory().close();  
    }  
}  

第三步:建立工具類就是把SessionFactory的方法單獨寫成工具類

package com.ygc.hibernate.utils;  
  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.AnnotationConfiguration;  
import org.hibernate.cfg.Configuration;  
  
public class HibernateUtils {  
    private HibernateUtils(){}  
    private static HibernateUtils hibernateUtils;  
    private HibernateUtils getHibernateUtils(){  
        if(hibernateUtils==null){  
            hibernateUtils = new HibernateUtils();  
        }  
        return hibernateUtils;  
    }  
      
    public static SessionFactory getFactory(){  
        Configuration configuration = new AnnotationConfiguration().configure();  
        return configuration.buildSessionFactory();  
    }  
} 

第四步:修改hibernate.cfg.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/hibernate</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">root</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.internal.NoCacheProvider</property>-->  
  
        <!-- Echo all executed SQL to stdout -->  
        <property name="show_sql">true</property>  
        <!--自動建立表-->  
       <property name="hbm2ddl.auto">create</property>  
  
        <!-- Drop and re-create the database schema on startup -->  
        <!--<property name="hbm2ddl.auto">update</property>-->  
  
        <!--<mapping resource="com/ygc/hibernate/modle/Students.hbm.xml"/>-->  
        <mapping class="com.ygc.hibernate.modle.Class"/>  
  
    </session-factory>  
  
</hibernate-configuration>  

第五步:新增log4j的配置檔案就是用來列印日誌的,記得新增log4j的jar包

# Configure logging for testing: optionally with log file  
# debug,info,warn,error,fatal  
log4j.rootLogger=debug, stdout, logfile  
  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n  
  
log4j.appender.logfile=org.apache.log4j.FileAppender  
log4j.appender.logfile.File=D:/logs/hibernate.log  
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout  
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n  
  
log4j.logger.org.hibernate.tool.hbm2ddl=debug  

最後一步執行檢視結果

C:\Documents and Settings\Administrator>mysql -uroot -proot  
Welcome to the MySQL monitor.  Commands end with ; or \g.  
Your MySQL connection id is 3  
Server version: 5.5.15 MySQL Community Server (GPL)  
  
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.  
  
Oracle is a registered trademark of Oracle Corporation and/or its  
affiliates. Other names may be trademarks of their respective  
owners.  
  
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. 

 
mysql> show databases;  
+--------------------+  
| Database           |  
+--------------------+  
| information_schema |  
| hibernate          |  
| hibernates         |  
| mysql              |  
| performance_schema |  
| test               |  
| xqwy               |  
+--------------------+  
7 rows in set (0.01 sec)  
mysql> show tables;  
+---------------------+  
| Tables_in_hibernate |  
+---------------------+  
| class               |  
| music               |  
| product             |  
| students            |  
| teacher             |  
| xuxudan             |  
+---------------------+  
6 rows in set (0.08 sec)  
  
mysql> select * from class;  
Empty set (0.00 sec)  
mysql> select * from class;  
+----+------------+---------+  
| id | className  | teacher |  
+----+------------+---------+  
|  1 | 大學二年級 | 田紅菊  |  
+----+------------+---------+  
1 row in set (0.00 sec)  
通過以上結果發現老師的身份證號碼沒有被插入到資料庫,說明我們新增的@transient有效了。