卖克的专栏

好记性不如烂笔头

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有效了。
阅读更多
个人分类: ORM
上一篇maven 解决jar冲突
下一篇hibernate返回前台时间搓是毫秒
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭