hibernate中如何用Annotion注解设置Modle中的字段不持久化

2017-01-06 10:08:28来源:oschina作者:vshcxl人点击

hibernate中Modle中的有些属性不想创建表是在数据库中产生字段保存数据,当这种需求是我们可以设置@transient表示透明的当设置此属性是在创建数据库是可以对此属性忽略,在本例中模拟了一个班级表表名为MyClass 属性有数据库id 班级名称 班级老师 老师身份证号 我们的需求想把老师身份证号不保存到数据库里不想对身份证不持久化数据解决方法很简单就是在对应的字段上面加@Transient的注解就搞定。


实例代码如下:


第一步:创建Java工程编写三个项目包把hibernate用的jar包添加到path里然后创建Modle类代码如下


packagecom.ygc.hibernate.modle;
importjava.io.Serializable;
importjavax.persistence.Basic;
importjavax.persistence.Entity;
importjavax.persistence.GeneratedValue;
importjavax.persistence.GenerationType;
importjavax.persistence.Id;
importjavax.persistence.Table;
importjavax.persistence.Transient;
@Entity
@Table(name="Class")//设置数据库表名为class
publicclassMyClassimplementsSerializable{
privateintid;
privateStringclassName;
privateStringteacher;
privateStringteacherNumber;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)//设置主键自动增长
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
@Basic
publicStringgetClassName(){
returnclassName;
}
publicvoidsetClassName(StringclassName){
this.className=className;
}
publicStringgetTeacher(){
returnteacher;
}
publicvoidsetTeacher(Stringteacher){
this.teacher=teacher;
}
//这是此注解后该属性不会数据持久化也是本例要说明的注解
@Transient
publicStringgetTeacherNumber(){
returnteacherNumber;
}
publicvoidsetTeacherNumber(StringteacherNumber){
this.teacherNumber=teacherNumber;
}
}

第二步:编写测试类就是Main方法的。


packagecom.ygc.hibernate.main;
importorg.hibernate.Session;
importcom.ygc.hibernate.modle.MyClass;
importcom.ygc.hibernate.utils.HibernateUtils;
publicclassClassTest{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
MyClassclas1=newMyClass();
clas1.setClassName("大学二年级");
clas1.setTeacher("田红菊");
clas1.setTeacherNumber("0100");
Sessionsession=HibernateUtils.getFactory().openSession();
session.beginTransaction();
session.save(clas1);
session.getTransaction().commit();
session.close();
HibernateUtils.getFactory().close();
}
}

第三步:创建工具类就是把SessionFactory的方法单独写成工具类


packagecom.ygc.hibernate.utils;
importorg.hibernate.SessionFactory;
importorg.hibernate.cfg.AnnotationConfiguration;
importorg.hibernate.cfg.Configuration;
publicclassHibernateUtils{
privateHibernateUtils(){}
privatestaticHibernateUtilshibernateUtils;
privateHibernateUtilsgetHibernateUtils(){
if(hibernateUtils==null){
hibernateUtils=newHibernateUtils();
}
returnhibernateUtils;
}
publicstaticSessionFactorygetFactory(){
Configurationconfiguration=newAnnotationConfiguration().configure();
returnconfiguration.buildSessionFactory();
}
}

第四步:修改hibernate.cfg.xml的配置文件

<?xmlversion='1.0'encoding='utf-8'?>
"-//Hibernate/HibernateConfigurationDTD3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



com.mysql.jdbc.Driver
jdbc:mysql://localhost/hibernate
root
root



org.hibernate.dialect.MySQLDialect





true

create





第五步:添加log4j的配置文件就是用来打印日志的,记得添加log4j的jar包


#Configureloggingfortesting:optionallywithlogfile
#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:/DocumentsandSettings/Administrator>mysql-uroot-proot
WelcometotheMySQLmonitor.Commandsendwith;or/g.
YourMySQLconnectionidis3
Serverversion:5.5.15MySQLCommunityServer(GPL)Copyright(c)2000,2010,Oracleand/oritsaffiliates.Allrightsreserved.OracleisaregisteredtrademarkofOracleCorporationand/orits
affiliates.Othernamesmaybetrademarksoftheirrespective
owners.Type'help;'or'/h'forhelp.Type'/c'toclearthecurrentinputstatement.

[sql]view plaincopy



print?

[sql]view plaincopy



print?

mysql>showdatabases;
+--------------------+
|Database|
+--------------------+
|information_schema|
|hibernate|
|hibernates|
|mysql|
|performance_schema|
|test|
|xqwy|
+--------------------+
7rowsinset(0.01sec)

[sql]view plaincopy



print?

mysql>showtables;
+---------------------+
|Tables_in_hibernate|
+---------------------+
|class|
|music|
|product|
|students|
|teacher|
|xuxudan|
+---------------------+
6rowsinset(0.08sec)mysql>select*fromclass;
Emptyset(0.00sec)


[sql]view plaincopy



print?

mysql>select*fromclass;
+----+------------+---------+
|id|className|teacher|
+----+------------+---------+
|1|大学二年级|田红菊|
+----+------------+---------+
1rowinset(0.00sec)

通过以上结果发现老师的身份证号码没有被插入到数据库,说明我们添加的@transient有效了。

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台