中文版hibernate-annotations-3.4.0.CR1-doc
Hibernate基础
查询条件的设定
借助的类有Criterion 及Expression,用来设置条件 Criteria criteria=session.createCriteria(Person.class); //创建Criterion,代表查询条件 Criterion criterion=Expression.eq(“name”,”zhangsan”); criteria.add(criterion).add(其他条件等等); List list=criteria.list();//执行查询并获得结果集合 //等同于hql=“from Person p where =‘zhangsan’”
O/R映射入门
application
SessionFactory
Session
今天hibernate关注 Session SessionFactory Configuration Transaction Query
TransactionFactory ConnectionProvider
Transaction
JDBC DB
Hibernate映射配置
DB定义 HBM映射文件 POJO类
POJO类:只包含getter和setter方法的类 HBM映射:是XML文件,用来描述类和表的 对应关系
Hibernate示例
创建一个Person表 CREATE TABLE person( id varchar(32) NOT NULL, name varchar(20) NOT NULL, password varchar(30) NOT NULL, sex varchar(2) default NULL, email varchar(20) default NULL, PRIMARY KEY (id) )
Hibernate工作原理及其作用(word文档良心出品)
Hibernate工作原理及其作用原理:1.读取并解析配置文件2.读取并解析映射信息,创建SessionFactory3.打开Sesssion4.创建事务Transation5.持久化操作6.提交事务7.关闭Session8.关闭SesstionFactory为什么要用:1. 对JDBC访问数据库的代码做了封装,大大简化了数据访问层繁琐的重复性代码。
2. Hibernate是一个基于JDBC的主流持久化框架,是一个优秀的ORM实现。
他很大程度的简化DAO层的编码工作3. hibernate使用Java反射机制,而不是字节码增强程序来实现透明性。
4. hibernate的性能非常好,因为它是个轻量级框架。
映射的灵活性很出色。
它支持各种关系数据库,从一对一到多对多的各种复杂关系。
2.Hibernate是如何延迟加载?1. Hibernate2延迟加载实现:a)实体对象b)集合(Collection)2. Hibernate3 提供了属性的延迟加载功能当Hibernate在查询数据的时候,数据并没有存在与内存中,当程序真正对数据的操作时,对象才存在与内存中,就实现了延迟加载,他节省了服务器的内存开销,从而提高了服务器的性能。
3.Hibernate中怎样实现类之间的关系?(如:一对多、多对多的关系)类与类之间的关系主要体现在表与表之间的关系进行操作,它们都市对对象进行操作,我们程序中把所有的表与类都映射在一起,它们通过配置文件中的many-to-one、one-to-many、many-to-many、4.说下Hibernate的缓存机制1. 内部缓存存在Hibernate中又叫一级缓存,属于应用事物级缓存2. 二级缓存:a) 应用及缓存b) 分布式缓存条件:数据不会被第三方修改、数据大小在可接受范围、数据更新频率低、同一数据被系统频繁使用、非关键数据c) 第三方缓存的实现5.Hibernate的查询方式Sql、Criteria,object comptosition Hql:1、属性查询2、参数查询、命名参数查询3、关联查询4、分页查询5、统计函数6.如何优化Hibernate?1.使用双向一对多关联,不使用单向一对多2.灵活使用单向一对多关联3.不用一对一,用多对一取代4.配置对象缓存,不使用集合缓存5.一对多集合使用Bag,多对多集合使用Set6. 继承类使用显式多态7. 表字段要少,表关联不要怕多,有二级缓存撑腰Hibernate的原理--ORM--------------------------------------------------------------------------1.启动Hibernate2.构建Configuration实例,初始化实例中的所有变量.Configuration cfg=new Configuration.configure();加载hibernate.cfg.xml文件至该实例(内存)通过hibernate.cfg.xml文件中的mapping节点配置并加载.hbm.xml文件至该实例(内存)3.利用上面创建的Configuration实例构建一个SessionFactory实例SessionFactory sessionFactory=cfg.getSessionFactory();4.由上面香到的SessionFactory实例创建连接Session=sessionFactory.getSession();5.由上面得到的Session实例创建事务操作接口,Transaction的一个实例txTransaction tx=session.beginTransaction();6.通过Session接口提供的各种方法操纵对数据库的访问.7.提交数据操作结果.mit();8.关闭数据连接.session.close();Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。
hibernate官方入门教程
hibernate官方入门教程第一部分-第一个Hibernate程序首先我们将创建一个简单的控制台(console-based)hibernate程序。
我们使用内置数据库(in-memory database) (HSQL DB),所以我们不必安装任何数据库服务器。
让我们假设我们希望有一个小程序可以保存我们希望关注的事件(Event)和这些事件的信息。
(译者注:在本教程的后面部分,我们将直接使用Event而不是它的中文翻译“事件”,以免混淆。
)我们做的第一件事是建立我们的开发目录,并把所有需要用到的Java库文件放进去。
从Hibernate网站的下载页面下载Hibernate分发版本。
解压缩包并把/lib下面的所有库文件放到我们新的开发目录下面的/lib目录下面。
看起来就像这样:.+libantlr.jarcglib-full.jarasm.jarasm-attrs.jarscommons-collections.jarcommons-logging.jarehcache.jarhibernate3.jarjta.jardom4j.jarlog4j.jarThis is the minimum set of required libraries (note that we also copied hibernate3.jar, the main archive) for Hibernate. See the README.txt file in the lib/ directory of the Hibernate distribution for more information about required and optional third-party libraries. (Actually,Log4j is not required but preferred by many developers.) 这个是Hibernate运行所需要的最小库文件集合(注意我们也拷贝了Hibernate3.jar,这个是最重要的库)。
hibernate_annotations
Hibernate Annotations Reference GuideVersion:3.4.0.GATable of Contents Preface (iv)1.Setting up an annotations project (1)1.1.Requirements (1)1.2.Configuration (1)1.3.Properties (2)1.4.Logging (3)2.Entity Beans (4)2.1.Intro (4)2.2.Mapping with EJB3/JPA Annotations (4)2.2.1.Declaring an entity bean (4)2.2.1.1.Defining the table (4)2.2.1.2.Versioning for optimistic locking (5)2.2.2.Mapping simple properties (5)2.2.2.1.Declaring basic property mappings (5)2.2.2.2.Declaring column attributes (7)2.2.2.3.Embedded objects(aka components) (7)2.2.2.4.Non-annotated property defaults (9)2.2..Mapping identifier properties (9)2.2.4.Mapping inheritance (12)2.2.4.1.Table per class (13)2.2.4.2.Single table per class hierarchy (13)2.2.4.3.Joined subclasses (13)2.2.4.4.Inherit properties from superclasses (14)2.2.5.Mapping entity bean associations/relationships (15)2.2.5.1.One-to-one (15)2.2.5.2.Many-to-one (17)2.2.5.3.Collections (18)2.2.5.4.Transitive persistence with cascading (23)2.2.5.5.Association fetching (24)2.2.6.Mapping composite primary and foreign keys (24)2.2.7.Mapping secondary tables (25)2.3.Mapping Queries (26)2.3.Mapping JPAQL/HQL queries.Mapping JPAQL/HQL queries (26)2.3.2.Mapping native queries (27)2.4.Hibernate Annotation Extensions (30)2.4.1.Entity (30)2.4.Identifier.Identifier (32)2.4.Identifier.1.Generators (32)2.4.Identifier.2.@NaturalId (33)2.4.3.Property (33)2.4.3.1.Access type (33)2.4.3.2.Formula (35)2.4.3.3.Type (35)2.4.3.4.Index (36)2.4.3.5.@Parent (36)2.4.3.6.Generated properties (36)2.4.3.7.@Target (36)2.4.3.8.Optimistic lock (37)Hibernate Annotations2.4.4.Inheritance (37)2.4.5.Single Association related annotations (37)zy options and fetching modes (38)2.4.5.2.@Any (39)2.4.6.Collection related annotations (39)2.4.6.1.Enhance collection settings (40)2.4.6.2.Extra collection types (40)2.4.7.Cascade (45)2.4.8.Cache (45)2.4.9.Filters (46)2.4.10.Queries (46)2.4.11.Custom SQL for CRUD operations (47)2.4.12.Tuplizer (48)Overriding metadata through XML.Overriding metadata through XML (50)Overriding metadata through XML.1.Principles (50)Overriding metadata through XML.1.1.Global level metadata (50)Overriding metadata through XML.1.2.Entity level metadata (50)Overriding metadata through XML.1.3.Property level metadata (53)Overriding metadata through XML.1.4.Association level metadata (53)4.Additional modules (55)4.1.Hibernate Validator (55)4.1.1.Description (55)4.1.2.Integration with Hibernate Annotations (55)4.2.Hibernate Search (56)4.2.1.Description (56)4.2.2.Integration with Hibernate Annotations (56)PrefaceHibernate,like all other object/relational mapping tools,requires metadata that governs the transformation of data from one representation to the other.In Hibernate2.x mapping metadata is most of the time declared in XML text files.Alternatively XDoclet can be used utilizing Javadoc source code annotations together with a compile time preprocessor.The same kind of annotation support is now available in the standard JDK,although more powerful and with better tools support.IntelliJ IDEA and Eclipse for example,support auto-completion and syntax highlighting of JDK5.0annotations which are compiled into the bytecode and read at runtime using reflection.No external XML files are needed.The EJB3specification recognizes the interest and the success of the transparent object/relational mapping paradigm.It standardizes the basic APIs and the metadata needed for any object/relational persistence mechan-ism.Hibernate EntityManager implements the programming interfaces and lifecycle rules as defined by the EJB3persistence specification and together with Hibernate Annotations offers a complete(and standalone) EJB3persistence solution on top of the mature Hibernate core.You may use a combination of all three togeth-er,annotations without EJB3programming interfaces and lifecycle,or even pure native Hibernate,depending on the business and technical needs of your project.At all times you cann fall back to Hibernate native APIs,or if required,even to native JDBC and SQL.This release of Hibernate Annotations is based on the final release of the EJB3.0/JPA specification(aka JSR-220[/en/jsr/detail?id=220])and supports all its features(including the optional ones).Hibernate specific features and extensions are also available through unstandardized,Hibernate specific annotations. While the Hibernate feature coverage is high,some can not yet be expressed via annotations.The eventual goal is to cover all of them.See the JIRA road map section for more informations.If you are moving from previous Hibernate Annotations versions,please have a look at Java Persistence migra-tion guide[/398.html].Chapter1.Setting up an annotations project1.1.Requirements•Download[/6.html]and unpack the Hibernate Annotations distribution from the Hibernate website.•This release requires Hibernate Core3.3and above.•This release is known to work on Hibernate Core3.3.0.SP1•Make sure you have JDK5.0installed or above.You can of course continue using XDoclet and get some of the benefits of annotation-based metadata with older JDK versions.Note that this document only describes JDK5.0annotations and you have to refer to the XDoclet documentation for more information.1.2.ConfigurationFirst,set up your classpath(after you have created a new project in your favorite IDE):•Copy all Hibernate3core and required3rd party library files(see lib/README.txt in Hibernate).•Copy hibernate-annotations.jar,lib/hibernate-comons-annotations.jar and lib/ ejb3-persistence.jar from the Hibernate Annotations distribution to your classpath as well.If you wish to use Hibernate Validator[],download it from the Hibernate website and add hibernate-validator.jar in your classpath.If you wish to use Hibernate Search[],download it from the Hibernate website and add hibernate-search.jar and lucene-core-x.y.z.jar in your classpath.We also recommend a small wrapper class to startup Hibernate in a static initializer block,known as Hibern-ateUtil.You might have seen this class in various forms in other areas of the Hibernate documentation.For Annotation support you have to enhance this helper class as follows:Interesting here is the use of AnnotationConfiguration.The packages and annotated classes are declared in your regular XML configuration file(usually hibernate.cfg.xml).Here is the equivalent of the above declara-tion:Note that you can mix the hbm.xml use and the new annotation one.The resource element can be either an hbm file or an EJB3XML deployment descriptor.The distinction is transparent for your configuration process. Alternatively,you can define the annotated classes and packages using the programmatic APIYou can also use the Hibernate EntityManager which has its own configuration mechanism.Please refer to this project documentation for more details.There is no other difference in the way you use Hibernate APIs with annotations,except for this startup routine change or in the configuration file.You can use your favorite configuration method for other properties(hi-bernate.properties,hibernate.cfg.xml,programmatic APIs,etc).You can even mix annotated persistent classes and classic hbm.cfg.xml declarations with the same SessionFactory.You can however not declare a class several times(whether annotated or through hbm.xml).You cannot mix configuration strategies(hbm vs annotations)in a mapped entity hierarchy either.To ease the migration process from hbm files to annotations,the configuration mechanism detects the mapping duplication between annotations and hbm files.HBM files are then prioritized over annotated metadata on a class to class basis.You can change the priority using hibernate.mapping.precedence property.The default is hbm,class,changing it to class,hbm will prioritize the annotated classes over hbm files when a conflict oc-curs.1.3.PropertiesAsides from the Hibernate core properties,Hibernate Annotations reacts to the following one1.4.LoggingHibernate Annotations utilizes Simple Logging Facade for Java[/](SLF4J)in order to log various system events.SLF4J can direct your logging output to several logging frameworks(NOP,Simple, log4j version1.2,JDK1.4logging,JCL or logback)depending on your chosen binding.In order to setup log-ging properly you will need slf4j-api.jar in your classpath together with the jar file for your preferred bind-ing-slf4j-log4j12.jar in the case of Log4J.See the SLF4J documentation [/manual.html]for more detail.The logging categories interesting for Hibernate Annotations are:Table1.1.Hibernate Annotations Log CategoriesCategory Functionorg.hibernate.cfg Log all configuration related events(not only annota-tions).For further category configuration refer to the Logging [/hib_docs/v3/reference/en/html_single/#configuration-logging]in the Hibernate Core documentation.Chapter2.Entity Beans2.1.IntroThis section covers EJB3.0(aka Java Persistence)entity annotations and Hibernate-specific extensions.2.2.Mapping with EJB3/JPA AnnotationsEJB3entities are plain POJOs.Actually they represent the exact same concept as the Hibernate persistent entit-ies.Their mappings are defined through JDK5.0annotations(an XML descriptor syntax for overriding is defined in the EJB3specification).Annotations can be split in two categories,the logical mapping annotations (allowing you to describe the object model,the class associations,etc.)and the physical mapping annotations (describing the physical schema,tables,columns,indexes,etc).We will mix annotations from both categories in the following code examples.EJB3annotations are in the javax.persistence.*package.Most JDK5compliant IDE(like Eclipse,IntelliJ IDEA and Netbeans)can autocomplete annotation interfaces and attributes for you(even without a specific "EJB3"module,since EJB3annotations are plain JDK5annotations).For more and runnable concrete examples read the JBoss EJB3.0tutorial or review the Hibernate Annotations test suite.Most of the unit tests have been designed to represent a concrete example and be a inspiration source.2.2.1.Declaring an entity beanEvery bound persistent POJO class is an entity bean and is declared using the@Entity annotation(at the class level):@Entity declares the class as an entity bean(i.e.a persistent POJO class),@Id declares the identifier property of this entity bean.The other mapping declarations are implicit.This configuration by exception concept is central to the new EJB3specification and a major improvement.The class Flight is mapped to the Flight table,using the column id as its primary key column.Depending on whether you annotate fields or methods,the access type used by Hibernate will be field or property.The EJB3spec requires that you declare annotations on the element type that will be accessed,i.e. the getter method if you use property access,the field if you use field access.Mixing EJB3annotations in both fields and methods should be avoided.Hibernate will guess the access type from the position of@Id or @EmbeddedId.Defining the table@Table is set at the class level;it allows you to define the table,catalog,and schema names for your entity bean mapping.If no@Table is defined the default values are used:the unqualified class name of the entity.The@Table element also contains a schema and a catalog attributes,if they need to be defined.You can also define unique constraints to the table using the@UniqueConstraint annotation in conjunction with@Table(for a unique constraint bound to a single column,refer to@Column).A unique constraint is applied to the tuple month,day.Note that the columnNames array refers to the logical column names.The logical column name is defined by the Hibernate NamingStrategy implementation.The default EJB3nam-ing strategy use the physical column name as the logical column name.Note that this may be different than the property name(if the column name is explicit).Unless you override the NamingStrategy,you shouldn't worry about that.Versioning for optimistic lockingYou can add optimistic locking capability to an entity bean using the@Version annotation:The version property will be mapped to the OPTLOCK column,and the entity manager will use it to detect con-flicting updates(preventing lost updates you might otherwise see with the last-commit-wins strategy).The version column may be a numeric(the recommended solution)or a timestamp as per the EJB3spec.Hi-bernate support any kind of type provided that you define and implement the appropriate UserVersionType. The application must not alter the version number set up by Hibernate in any way.To artificially increase the version number,check in Hibernate Entity Manager's reference documentation LockMode.WRITE2.2.2.Mapping simple propertiesDeclaring basic property mappingsEvery non static non transient property(field or method)of an entity bean is considered persistent,unless you annotate it as@Transient.Not having an annotation for your property is equivalent to the appropriate@Basic annotation.The@Basic annotation allows you to declare the fetching strategy for a property:counter,a transient field,and lengthInMeter,a method annotated as@Transient,and will be ignored by the entity ,length,and firstname properties are mapped persistent and eagerly fetched(the default for simple properties).The detailedComment property value will be lazily fetched from the database once a lazy property of the entity is accessed for the first ually you don't need to lazy simple properties(not to be confused with lazy association fetching).NoteTo enable property level lazy fetching,your classes have to be instrumented:bytecode is added to the original one to enable such feature,please refer to the Hibernate reference documentation.If your classes are not instrumented,property level lazy loading is silently ignored.The recommended alternative is to use the projection capability of EJB-QL or Criteria queries.EJB3support property mapping of all basic types supported by Hibernate(all basic Java types,their respective wrappers and serializable classes).Hibernate Annotations support out of the box Enum type mapping either in-to a ordinal column(saving the enum ordinal)or a string based column(saving the enum string representation): the persistence representation,defaulted to ordinal,can be overriden through the@Enumerated annotation as shown in the note property example.In core Java APIs,the temporal precision is not defined.When dealing with temporal data you might want to describe the expected precision in database.Temporal data can have DATE,TIME,or TIMESTAMP precision(ie the actual date,only the time,or both).Use the@Temporal annotation to fine tune that.@Lob indicates that the property should be persisted in a Blob or a Clob depending on the property type: java.sql.Clob,Character[],char[]and ng.String will be persisted in a Clob.java.sql.Blob, Byte[],byte[]and serializable type will be persisted in a Blob.If the property type implements java.io.Serializable and is not a basic type,and if the property is not annot-ated with@Lob,then the Hibernate serializable type is used.Declaring column attributesThe column(s)used for a property mapping can be defined using the@Column e it to override de-fault values(see the EJB3specification for more information on the defaults).You can use this annotation at the property level for properties that are:•not annotated at all•annotated with@Basic•annotated with@Version•annotated with@Lob•annotated with@Temporal•annotated with@org.hibernate.annotations.CollectionOfElements(for Hibernate only)The name property is mapped to the flight_name column,which is not nullable,has a length of50and is not updatable(making the property immutable).This annotation can be applied to regular properties as well as@Id or@Version properties.(1)name(optional):the column name(default to the property name)(2)unique(optional):set a unique constraint on this column or not(default false)(3)nullable(optional):set the column as nullable(default true).(4)insertable(optional):whether or not the column will be part of the insert statement(default true)(5)updatable(optional):whether or not the column will be part of the update statement(default true)(6)columnDefinition(optional):override the sql DDL fragment for this particular column(non portable)(7)table(optional):define the targeted table(default primary table)(8)length(optional):column length(default255)(8)precision(optional):column decimal precision(default0)(10)scale(optional):column decimal scale if useful(default0)Embedded objects(aka components)It is possible to declare an embedded component inside an entity and even override its column -ponent classes have to be annotated at the class level with the@Embeddable annotation.It is possible to overridethe column mapping of an embedded object for a particular entity using the@Embedded and@AttributeOverride annotation in the associated property:A embeddable object inherit the access type of its owning entity(note that you can override that using the Hi-bernate specific@AccessType annotations(see Hibernate Annotation Extensions).The Person entity bean has two component properties,homeAddress and bornIn.homeAddress property has notbeen annotated,but Hibernate will guess that it is a persistent component by looking for the@Embeddable an-notation in the Address class.We also override the mapping of a column name(to bornCountryName)with the@Embedded and@AttributeOverride annotations for each mapped attribute of Country.As you can see,Coun-try is also a nested component of Address,again using auto-detection by Hibernate and EJB3defaults.Over-riding columns of embedded objects of embedded objects is currently not supported in the EJB3spec,however, Hibernate Annotations supports it through dotted expressions.)You can annotate a embedded object with the@MappedSuperclass annotation to make the superclass properties persistent(see@MappedSuperclass for more informations).While not supported by the EJB3specification,Hibernate Annotations allows you to use association annota-tions in an embeddable object(ie@*ToOne nor@*ToMany).To override the association columns you can use @AssociationOverride.If you want to have the same embeddable object type twice in the same entity,the column name defaulting will not work:at least one of the columns will have to be explicit.Hibernate goes beyond the EJB3spec and allows you to enhance the defaulting mechanism through the NamingStrategy.DefaultComponentSafeNaming-Strategy is a small improvement over the default EJB3NamingStrategy that allows embedded objects to be de-faulted even if used twice in the same entity.Non-annotated property defaultsIf a property is not annotated,the following rules apply:•If the property is of a single type,it is mapped as@Basic•Otherwise,if the type of the property is annotated as@Embeddable,it is mapped as@Embedded •Otherwise,if the type of the property is Serializable,it is mapped as@Basic in a column holding the object in its serialized version•Otherwise,if the type of the property is java.sql.Clob or java.sql.Blob,it is mapped as@Lob with the ap-propriate LobType2.2..Mapping identifier propertiesThe@Id annotation lets you define which property is the identifier of your entity bean.This property can be set by the application itself or be generated by Hibernate(preferred).You can define the identifier generation strategy thanks to the@GeneratedValue annotation:•AUTO-either identity column,sequence or table depending on the underlying DB•TABLE-table holding the id•IDENTITY-identity column•SEQUENCE-sequenceHibernate provides more id generators than the basic EJB3ones.Check Hibernate Annotation Extensions for more informations.The following example shows a sequence generator using the SEQ_STORE configuration(see below)The next example uses the identity generator:The AUTO generator is the preferred type for portable applications(across several DB vendors).The identifier generation configuration can be shared for several@Id mappings with the generator attribute.There are several configurations available through@SequenceGenerator and@TableGenerator.The scope of a generator can be the application or the class.Class-defined generators are not visible outside the class and can override applica-tion level generators.Application level generators are defined at XML level(see Chapter Overriding metadata through XML,Overriding metadata through XML):If JPA XML(like META-INF/orm.xml)is used to define thegenerators,EMP_GEN and SEQ_GEN are application level generators.EMP_GEN defines a table based id generator using the hilo algorithm with a max_lo of20.The hi value is kept in a table"GENERATOR_TABLE".The information is kept in a row where pkColumnName"key"is equals to pkColumnValue"EMP"and column valueColumnName"hi"contains the the next high value used.SEQ_GEN defines a sequence generator using a sequence named my_sequence.The allocation size used for this sequence based hilo algorithm is20.Note that this version of Hibernate Annotations does not handle initial-Value in the sequence generator.The default allocation size is50,so if you want to use a sequence and pickup the value each time,you must set the allocation size to1.NotePackage level definition is no longer supported by the EJB3.0specification.However,you can use the @GenericGenerator at the package level(see Section2.4.Identifier,“Identifier”).The next example shows the definition of a sequence generator in a class scope:This class will use a sequence named my_sequence and the SEQ_STORE generator is not visible in other classes.Note that you can check the Hibernate Annotations tests in the<package>org.hibernate.test.annotations.id</package>package for more examples.You can define a composite primary key through several syntaxes:•annotate the component property as@Id and make the component class@Embeddable•annotate the component property as@EmbeddedId•annotate the class as@IdClass and annotate each property of the entity involved in the primary key with @IdWhile quite common to the EJB2developer,@IdClass is likely new for Hibernate users.The composite primary key class corresponds to multiple fields or properties of the entity class,and the names of primary key fields or properties in the primary key class and those of the entity class must match and their types must be the same.Let's look at an example:As you may have seen,@IdClass points to the corresponding primary key class.While not supported by the EJB3specification,Hibernate allows you to define associations inside a composite identifier.Simply use the regular annotations for that2.2.4.Mapping inheritanceEJB3supports the three types of inheritance:•Table per Class Strategy:the<union-class>element in Hibernate•Single Table per Class Hierarchy Strategy:the<subclass>element in Hibernate•Joined Subclass Strategy:the<joined-subclass>element in HibernateThe chosen strategy is declared at the class level of the top level entity in the hierarchy using the@Inheritance annotation.NoteAnnotating interfaces is currently not supported.Table per classThis strategy has many drawbacks(esp.with polymorphic queries and associations)explained in the EJB3 spec,the Hibernate reference documentation,Hibernate in Action,and many other places.Hibernate work around most of them implementing this strategy using SQL UNION queries.It is commonly used for the top level of an inheritance hierarchy:This strategy support one to many associations provided that they are bidirectional.This strategy does not sup-port the IDENTITY generator strategy:the id has to be shared across several tables.Consequently,when using this strategy,you should not use AUTO nor IDENTITY.Single table per class hierarchyAll properties of all super-and subclasses are mapped into the same table,instances are distinguished by a spe-cial discriminator column:Plane is the superclass,it defines the inheritance strategy InheritanceType.SINGLE_TABLE.It also defines the discriminator column through the@DiscriminatorColumn annotation,a discriminator column can also define the discriminator type.Finally,the@DiscriminatorValue annotation defines the value used to differentiate a class in the hierarchy.All of these attributes have sensible default values.The default name of the discriminator column is DTYPE.The default discriminator value is the entity name(as defined in@)for Discrim-inatorType.STRING.A320is a subclass;you only have to define discriminator value if you don't want to use the default value.The strategy and the discriminator type are implicit.@Inheritance and@DiscriminatorColumn should only be defined at the top of the entity hierarchy.Joined subclassesThe@PrimaryKeyJoinColumn and@PrimaryKeyJoinColumns annotations define the primary key(s)of the joined subclass table:All of the above entities use the JOINED strategy,the Ferry table is joined with the Boat table using the same primary key names.The AmericaCupClass table is joined with Boat using the join condition Boat.id=Amer-icaCupClass.BOAT_ID.Inherit properties from superclassesThis is sometimes useful to share common properties through a technical or a business superclass without in-cluding it as a regular mapped entity(ie no specific table for this entity).For that purpose you can map them as @MappedSuperclass.In database,this hierarchy will be represented as an Order table having the id,lastUpdate and lastUpdater columns.The embedded superclass property mappings are copied into their entity subclasses.Remember that the embeddable superclass is not the root of the hierarchy though.NoteProperties from superclasses not mapped as@MappedSuperclass are ignored.NoteThe access type(field or methods),is inherited from the root entity,unless you use the Hibernate an-notation@AccessTypeNoteThe same notion can be applied to@Embeddable objects to persist properties from their superclasses.You also need to use@MappedSuperclass to do that(this should not be considered as a standard EJB3 feature though)NoteIt is allowed to mark a class as@MappedSuperclass in the middle of the mapped inheritance hierarchy.NoteAny class in the hierarchy non annotated with@MappedSuperclass nor@Entity will be ignored.You can override columns defined in entity superclasses at the root entity level using the@AttributeOverride annotation.)The altitude property will be persisted in an fld_altitude column of table Plane and the propulsion associ-ation will be materialized in a fld_propulsion_fk foreign key column.You can define@AttributeOverride(s)and@AssociationOverride(s)on@Entity classes, @MappedSuperclass classes and properties pointing to an@Embeddable object.2.2.5.Mapping entity bean associations/relationshipsOne-to-oneYou can associate entity beans through a one-to-one relationship using@OneToOne.There are three cases for one-to-one associations:either the associated entities share the same primary keys values,a foreign key is held by one of the entities(note that this FK column in the database should be constrained unique to simulate one-to-one multiplicity),or a association table is used to store the link between the2entities(a unique constraint has to be defined on each fk to ensure the one to one multiplicity)First,we map a real one-to-one association using shared primary keys:。
NHibernate中文文档
第1章NHibernate体系结构总览对NHibernate体系结构的非常高层的概览:这幅图展示了NHibernate使用数据库和配置文件数据来为应用程序提供持久化服务(和持久化的对象)。
我们试图显示更多NHibernate运行时体系结构的细节。
但挺不幸的,NHibernate是比较灵活的并且提供了好几种不同的运行方式。
我们展示一下两种极端情况。
轻型体系中,应用程序自己提供连接,并且自行管理事务。
这种方式使用了NHibernate API的一个最小子集。
全面解决体系中,对于应用程序来说,所有的底层 API都被抽象了,NHibernate会替你照管所有的细节。
下面是图中一些对象的定义:(NHibernate.ISessionFactory) 对属于单一数据库的编译过的映射文件的一个线程安全的,不可变的缓存快照。
它是Session的工厂,是ConnectionProvider的客户。
可以持有一个可选的(第二级)数据缓存,可以在进程级别或集群级别保存可以在事物中重用的数据。
第2章ISessionFactory配置目录可编程配置方式获取ISessionFactory用户自行提供连接NHibernate提供连接可选配置属性SQL 方言(SQL Dialects)外连接抓取(Outer Join Fetching )自定义CacheProvider查询语言替换Logging因为NHibernate被设计为可以在许多不同环境下工作,所以它有很多配置参数。
幸运的是,大部分都已经有默认值了。
NHibernate.Test.dll包含了一个示例的配置文件app.config,它演示了一些可变的参数。
可编程配置方式NHibernate.Cfg.Configuration的一个实例代表了应用程序中所有的.NET类到SQL数据库的映射的集合。
Configuration用于构造一个(不可变的)ISessionFactory。
hibernate annotations
第七章Hibernate Annotations本章学习目标熟练掌握使用Hibernate Annotations的使用进一步掌握Hibernate的使用本章技能目标使用Hibernate Annotation进行开发本章简介近来,越来越多的软件开发公司开始使用Annotations替代xml配置进行DAO开发,因为Annotations 使用起来比较简单,所以很受程序员的喜欢,本章将详细向大家讲解如何使用Annotations进行相关应用的开发。
7.1. 系统需求首先从Hibernate官方网站下载并解压Hibernate Annotations的发布包。
这个版本(预览版)要求使用Hibernate 3.2.0.CR2或更高版本。
请不要和老版本的Hibernate 3.x混合起来使用。
这个版本在Hibernate core 3.2.0.CR2的基础上工作良好。
首先确定你已经安装了JDK 5.0。
当然就算使用低版本的JDK, Xdoclet 也可以提供(基于注解的)元数据所带来的部分功能。
7.1.2. 系统配置首先就是设置classpath(当然是在IDE中创建了一个新项目之后)。
将这里比较有意思的是使用到了AnnotationConfiguration类。
在XML配置文件(通常是hibernate.cfg.xml)中则定义了包和经过注解的类。
下面的xml和前面的声明等价:注意现在你可以混合使用hbm.xml和注解。
资源元素(resource element)可以是hbm文件也可以是EJB3 XML发布描述符,此差别对于配置过程是透明的。
除了上面的方式,你还可以通过编程的方式定义包括注解的类和包你也可以使用Hibernate Entity Manager来完成以上功能。
除了启动方式和配置文件有所改变之外,结合注解来使用Hibernate API和以前没有什么区别,在其他方面你还是可以继续保持以前的习惯和喜好(hibernate.properties,hibernate.cfg.xml,programmatic APIs等等)。
hibernate_annotation
Hibernate Annotation 使用hibernate Annotation来映射实体准备工作下载hibernate-distribution-3.3.2.GAhibernate-annotations-3.4.0.GAslf4j导入相关依赖包Hibernate HOME:\hibernate3.jar\lib\bytecode(二进制)\lib\optional(可选的)\lib\required(必须的)导入required下的所有jar包antlr-2.7.6.jarcommons-collections-3.1.jardom4j-1.6.1.jarhibernate3.jarjavassist-3.9.0.GA.jarjta-1.1.jarslf4j-api-1.5.10.jarslf4j-log4j12-1.5.10.jarlog4j-1.2.14.jarmysql.jar---Annotation包ejb3-persistence.jarhibernate-annotations.jarhibernate-commons-annotations.jar简单的例子,通过annotation注解来映射实体PO1、建立(Java Project)项目:hibernate_0100_annotation_HelloWorld_default2、在项目根下建立lib目录a)导入相关依赖jar包antlr-2.7.6.jarcommons-collections-3.1.jardom4j-1.6.1.jarejb3-persistence.jarhibernate-annotations.jarhibernate-commons-annotations.jarhibernate3.jarjavassist-3.9.0.GA.jarjta-1.1.jarlog4j-1.2.14.jarmysql.jarslf4j-api-1.5.10.jarslf4j-log4j12-1.5.10.jar3、建立PO持久化类cn.serup.model.Teacher 内容如下package cn.serup.model;import javax.persistence.Entity;import javax.persistence.Id;//@Entity表示该是实体类@Entitypublic class Teacher {private int id ;private String username ;private String password ;//ID为主键,主键手动分配@Idpublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {ername = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}4、在src目录中建立hibernate.cfg.xml(hibernate配置文件)文件,内容如下<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="connection.url">jdbc:mysql://localhost/hibernate</property> <property name="ername">root</property><property name="connection.password">saber</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="show_sql">true</property><!-- 独立线程运行,如果通过getCurrentSession()来获得Session,需要设置如下 --><property name="current_session_context_class">thread</property><!-- 映射持久化类 --><mapping class="cn.serup.model.Teacher"/></session-factory></hibernate-configuration>5.、建立新的源码包testa)编写单元测试,结构如下cn.serup.hibernate.test.TeacherTest 内容如下:package cn.serup.hibernate.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import org.hibernate.tool.hbm2ddl.SchemaExport;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;import cn.serup.model.Teacher;public class TeacherTest {private static SessionFactory sessionFactory ;@Testpublic void testSaveTeacher() {Teacher t = new Teacher() ;t.setId(2) ;t.setUsername("努尔哈赤") ;t.setPassword("12345") ;Session session = sessionFactory.getCurrentSession() ;session.beginTransaction() ;session.save(t) ;session.beginTransaction().commit() ;}@BeforeClasspublic static void beforeClass() {new SchemaExport(new AnnotationConfiguration().configure()).create(true, true) ;sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory() ;}@AfterClasspublic static void afterClass() {sessionFactory.close() ;}}Annotation表名称与字段映射,长度1、项目:hibernate_0200_annotation_column2、表名称映射,在默认情况下使用@Entity,则使用类名做为表名3、所有的注解写在get()方法上面4、表名映射a)@Table(name="t_teacher")3、字段映射a)默认情况下,则使用属性名称来作为列名(字段名)b)在get()方法上写注解i.@Column(name="t_username")ii.长度iii.@Column(name="t_username",length=35)c)默认情况下会将所有的属性映射到表中,如果不想某个属性映射到表中,如下编写i.@Transient(瞬时、临时(或者透明))Annotation映射主键属性(ID生成策略)1、项目:hibernate_0300_annotation_ID2、使用@Id注解可以将实体bean中的某个属性定义为标识符(identifier),该属性的值可以通过应用自身进行设置(ID手动分配,但不能重复)3、(EJB3规范)也可以通过Hiberante生成(推荐). 使用@GeneratedValue注解可以定义该标识符的生成策略:∙AUTO - 可以是identity column类型,或者sequence类型或者table类型,取决于不同的底层数据库.∙TABLE - 使用表保存id值∙IDENTITY - identity column∙SEQUENCE - sequenceAUTO相当于XML映射文件中的Native4、AUTO ,写上@GeneratedValue则会默认选择AUTO来生成主键,会根据你的方言来选择数据库提供的自增机制,作为主键的生产策略,如果数据库是MySQL,则使用auto_increment@Id@GeneratedValue//或者@GeneratedValue(strategy=GenerationType.AUTO)public int getId() { .... }5、IDENTITY 取得最大的ID值+1,作为主键@Id@GeneratedValue(strategy=GenerationType.IDENTITY)public int getId() { .... }6、TABLE 使用hilo(高低位算法,来产生主键)@Id@GeneratedValue(strategy=GenerationType.TABLE)public int getId() { .... }7、SEQUENCE Oracle的自增机制@Id@GeneratedValue(strategy=GenerationType.SEQUENCE)public int getId() { .... }使用Oracle的SEQUENCE 的话。
Hibernate Annotation帮助文档
Hibernate Annotations参考文档3.2.0 CR1目录前言1. 翻译说明2. 版权声明前言1. 创建一个注解项目1.1. 系统需求1.2. 系统配置2. 实体Bean2.1. 简介2.2. 用EJB3注解进行映射2.2.1. 声明实体bean2.2.1.1. 定义表(Table)2.2.1.2. 乐观锁定版本控制2.2.2. 映射简单属性2.2.2.1. 声明基本的属性映射2.2.2.2. 声明列属性2.2.2.3. 嵌入式对象(又名组件)2.2.2.4. 无注解之属性的默认值2.2.. 映射主键属性2.2.4. 映射继承关系2.2.4.1. 每个类一张表2.2.4.2. 每个类层次结构一张表2.2.4.3. 连接的子类2.2.4.4. 从父类继承的属性2.2.5. 映射实体Bean的关联关系2.2.5.1. 一对一(One-to-one)2.2.5.2. 多对一(Many-to-one)2.2.5.3. 集合类型2.2.5.4. 用cascading实现传播性持久化(Transitive persistence)2.2.5.5. 关联关系获取2.2.6. 映射复合主键与外键2.2.7. 映射二级表(secondary tables)2.3. 映射查询2.3.1. 映射EJBQL/HQL查询2.3.2. 映射本地化查询2.4. Hibernate独有的注解扩展2.4.1. 实体2.4.2. 标识符2.4.3. 属性2.4.3.1. 访问类型2.4.3.2. 公式2.4.3.3. 类型2.4.3.4. 索引2.4.3.5. @Parent2.4.3.6. 生成的属性2.4.4. 继承2.4.5. 关于单个关联关系的注解2.4.5.1. 延迟选项和获取模式2.4.6. 关于集合类型的注解2.4.6.1. 参数注解2.4.6.2. 更多的集合类型2.4.7. 缓存2.4.8. 过滤器2.4.9. 查询3. 通过XML覆写元数据3.1. 原则3.1.1. 全局级别的元数据3.1.2. 实体级别的元数据3.1.3. 属性级别的元数据3.1.4. 关联级别的元数据4. Hibernate验证器4.1. 约束4.1.1. 什么是约束?4.1.2. 内建约束4.1.3. 错误信息4.1.4. 编写你自己的约束4.1.5. 注解你的领域模型4.2. 使用验证器框架4.2.1. 数据库schema层次验证4.2.2. Hibernate基于事件的验证4.2.3. 程序级验证4.2.4. 验证信息5. Hibernate与Lucene集成5.1. 使用Lucene为实体建立索引5.1.1. 注解领域模型5.1.2. 启用自动索引A. 术语表前言WARNING! This is a translated version of the English Hibernate reference documentation. The translated version might not be up to date! However, the differences should only be very minor. Consult the English reference documentation if you are missing information or encounter a translation error. If you like to contribute to a particular translation, contact us on the Hibernate developer mailing list.Translator(s): RedSaga Translate Team 满江红翻译团队 <caoxg@> 1. 翻译说明本文档的翻译是在网络上协作进行的,也会不断根据Hibernate的升级进行更新。
Hibernate4开发文档
hibernate4简介开源的对象关系映射框架(ORM)hibernate 核心接口Session接口Session接口负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流SessionFactory接口SessionFactory接口负责初始化Hibernate。
它充当数据存储源的代理,并负责创建Session对象Configuration类Configuration类负责配置并启动Hibernate,创建SessionFactory 对象。
在Hibernate的启动的过程中,Configuration类的实例首先定位映射文档位置、读取配置,然后创建SessionFactory对象Transaction接口Transaction接口负责事务相关的操作Query和Criteria接口Query和Criteria接口负责执行各种数据库查询。
它可以使用HQL语句或SQL语句两种表达方式。
hibernate 访问持久化类属性的策略accessproperty:field:hibernate 主键策略generator 主键生成器increment 自动增长数据类型long short intidentity sql server mysql自动增长long shorintnative 根据数据库的支持自动选择identity sequence hilo uuidhilo<generator class="hilo"><param name="table">hi_value</param><param name="column">next_value</param><param name="max_lo">100</param></generator>sequence 序列必须有一个序列名称assigned 自然主键主键由java程序指定hibernate 对象状态瞬时态瞬时对象在内存孤立存在,它是携带信息的载体,不和数据库的数据有任何关联关系new 对象delete()持久态处于该状态的对象在数据库中具有对应的记录,并拥有一个持久化标识save() saveOrUpdate() get() load()脱管态当一个session执行close()或clear()、evict()之后当与某持久对象关联的session被关闭后,该持久对象转变为脱管对象关系hibernate4 注解和关系hibernate4 注解@Entity 表示该类是一个实体类@Table 映射成一张表不写参数默认表名跟类名相同@Table(name="t_people")@Id 表示主键@GeneratedValue(strategy=GenerationType.AUTO)(native)@Id@GeneratedValue(generator="seq_ganerator")@GenericGenerator(name="seq_ganerator",strategy="sequence",parameters={@Parameter(name="sequence",value="seq_people")})1、native@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "native")2、uuid@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "uuid") 3、hilo@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "hilo") 4、assigned@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "assigned")5、identity@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "identity")6、select@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name="select", strategy="select",parameters = { @Parameter(name = "key", value = "idstoerung") })7、sequence@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "sequence",parameters = { @Parameter(name = "sequence", value = "seq_payablemoney") })8、seqhilo@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "seqhilo", parameters = { @Parameter(name = "max_lo", value = "5") })9、increment@GeneratedValue(generator = "paymentableGenerator")@GenericGenerator(name = "paymentableGenerator", strategy = "increment")10、foreign@GeneratedValue(generator = "idGenerator")@GenericGenerator(name = "idGenerator", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })@Transient该注解可以屏蔽属性的映射hibernate 延迟加载getget方法一要一执行就会发出sql get没有延迟加载如果对象不存在会抛出ng.NullPointerExceptionload调用load方法时并不会发出sql语句,只有在使用该对象时才发会sql, 当完成load之后,其实拿到的是一个代理对象,这个代理对象只有一个id值,获取对象的其它值时,才会发sql 语句load 用到了hibernate的延迟加载如果对象不存会抛出org.hibernate.ObjectNotFoundException:一对一关联OneToOne单向关联<!--oneToone是many-to-one的一个特例只须要增加unique=true(唯一) cascade 表示级联(all delete none save saveorupdate--><many-to-one name="person" column="pid" unique="true" cascade="delete" ></many-to-one> 单向关联注解@OneToOne@JoinColumn(name="pid",unique=true)cascade属性的可选值:all : 所有情况下均进行关联操作。
Hibernate
课程内容1.HelloWorlda)xmlb)annotation2.Hibernate原理模拟–什么是O/RMapping以及为什么要有O/RMapping3.常见的O/R框架(了解)4.hibernate基础配置(重点)5.ID生成策略(重点掌握AUTO)6.Hibernate核心开发接口介绍(重点)7.对象的三种状态(了解)8.关系映射(重点)9.Hibernate查询(HQL)10.在Struts基础上继续完善BBS200911.性能优化(重点)12.补充话题风格1.先脉络,后细节2.先操作,后原理3.重Annotation,轻xml配置文件a)JPAb)hibernate - extension资源1.2.hibernate zh_CN文档3.hibernate annotation references环境准备1.下载hibernate3.3.22.下载hibernate3.4.03.注意阅读hibernate compatibility matrix(hibernate网站,download)4.下载slf4j1.5.8Hibernate HelloWorld1.建立新的java项目,名为:hibernate_0100_HelloWorld2.学习建立User-library – hibernate,并加入相应的jar包a)项目右键-build path-configure build path-add libraryb)选择User-library,在其中新建libraray,命名为hibernatec)在该library中加入hibernate所需jar包i.hibernate coreii./requirediii.slf-nop jar3.引入mysql的JDBC驱动包4.在mysql中建立对应的数据库以及表a)create database hibernate;b)use hibernate;c)create table Student (id int primary key, name varchar(20), age int);5.建立hibernate配置文件hibernate.cfg.xmla)从参考文档中copyb)修改对应的数据库连接c)注释掉暂时用不上的内容6.建立Student类7.建立Student映射文件Student.hbm.xmla)参考文档8.将映射文件加入到hibernate.cfg.xml中a)参考文档9.写测试类Main,在Main中对Student对象进行直接的存储测试a)参考文档10.FAQ:a)要调用new Configuration().configure().buildSessionFactory(),而不是省略configure,否则会出hibernate dialect must be set的异常11.Note:a)请务必建立自己动手查文档的能力b)重要的是:i.要建立自己动手查一手文档的信心ii.还有建立自己动手查一手文档的习惯!iii.主动学习,放弃被动接受灌输的习惯!12.建立能力:a)错误读完整b)读出错误的关键行c)排除法d)比较法e)google老师建立Annotation版本的HelloWorld1.创建teacher表,create table teacher (id int primary key, name varhcar(20), titlevarchar(10));2.创建Teacher类3.在hibernate lib中加入annotation的jar包a)hibernate annotaion jarb)ejb3 persistence jarc)hibernate common annotations jard)注意文档中没有提到hibernate-common-annotations.jar文件4.参考Annotaion文档建立对应的注解5.在hibernate.cfg.xml中建立映射<mapping class=…/>6.参考文档进行测试(注意文档中缺少configure()的小bug)7.FAQ: @不给提示a)content assist – activation –加上@What is and Why O/R Mapping1.JDBC操作数据库很繁琐2.Sql语句编写并不是面向对象的3.可以在对象和关系表之间建立关联来简化编程4.O/R Mapping简化编程5.O/R Mapping跨越数据库平台6.Hibernate_0200_OR_Mapping_SimulationO/R Mapping Frameworks1.hibernate2.toplink3.jdo4.JPAa)意愿统一天下Hibernate基础配置1.对应项目:Hibernate_0300_BasicConfiguration2.介绍MySQL的图形化客户端3.hibernate.cfg.xml:hbm2ddl.autoa)先建表还是先建实体类4.搭建日志环境并配置显示DDL语句a)slf4j与log4j的关系:slf4j像是一个大管家,可以管理许多的日志框架,log4j是其中之一b)加入sl4j-log4j.jar,加入log4j的jar包,去掉slf4j-nop-jarc)从hibernate/project/etc目录copy log4j.propertiesd)查询hibernate文档,日志部分,调整日志的输出策略e)5.搭建JUnit环境a)需要注意JUnit的Bug6.hibernate.cfg.xml:show_sql7.hibernate.cfg.xml:format_sql8.表名和类名不同,对表名进行配置a)Annotation: @Tableb)xml:自己查询9.字段名和属性相同a)默认为@Basicb)xml中不用写column10.字段名和属性名不同a)Annotation: @Columnb)xml:自己查询11.不需要psersistence的字段a)Annotation:@Transientb)xml不写12.映射日期与时间类型,指定时间精度a)Annotation:@Temporalb)xml:指定type13.映射枚举类型a)@Enumeratedb)xml:麻烦14.字段映射的位置(field或者get方法)a)best practice:保持field和get set方法的一致15.@Lob16.课外:CLOB BLOB类型的数据存取17.课外:Hibernate自定义数据类型18.hibernate类型a)ID生成策略1.对应项目:hibernate_0400_ID2.注意:a)我们观察hibernate生成表的结构并不是为了将来就用它生成,(可能还有自己的扩展,比如index等)而是为了明白我们应该建立什么样的表和实体类映射3.xml生成ida)generatorb)常用四个:native identity sequence uuid4.@GeneratedValuea)自定义IDb)AUTOi.默认:对MySQL,使用auto_incrementii.对Oracle使用hibernate_sequence(名称固定)c)IDENTITYd)SEQUENCEi.@SequenceGeneratore)TABLE (可以忘记)i.@TableGenerator5.FAQ:a)用Junit测试时Hibernate SessionFactory 初始化异常不提示。
Hibernate4之配置详解
Hibernate4之配置详解Hibernate基本配置其实就是SessionFactory的配置,所有配置都在<session-factory/>标签之内。
但是<session-factory/>标签又可以分成3个部分的配置:1.JDBC连接参数的基本配置2.Hibernate连接池的参数配置3.注册ORM映射文件的配置Hibernate4和Hibernate3在配置上的一些区别:连接池c3p0的配置由于Hibernate自己实现的连接池不太好,在项目中,建议使用工业级的连接池,比如:c3p0,Hibernate发行包中带有c3p0的专用jar包hibernate-c3p0-4.1.4.Final.jar,在以前的Hibernate3.X版本中是直接在核心jar包里面的,在4.X版本之后包名做出来调整,大家使用的时候需要注意了。
TransactionFactory有三个标准(内建)的选择:1:委托给数据库(JDBC)事务(默认)Hibernate3:org.hibernate.transaction.JDBCTransactionFactor yHibernate4:org.hibernate.engine.transaction.internal.jdbc.JD BCTransactionFactory2:JTA事务,如果在上下文环境中存在运行着的事务(如, EJB会话Bean的方法), 则委托给容器管理的事务, 否则,将启动一个新的事务,并使用Bean管理的事务.Hibernate3: org.hibernate.transaction.JTATransactionFactory Hibernate4:org.hibernate.engine.transaction.internal.jta.JTATransactionFacto ry3:委托给容器管理的JTA事务Hibernate3:org.hibernate.transaction.CMTTransactionFactoryHibernate4:org.hibernate.engine.transaction.internal.jta.CM TTransactionFactory也可以定义属于你自己的事务策略 (如, 针对CORBA的事务服务)Hibernate4连接池C3P0基本配置Xml代码1.<?xml version="1.0" encoding="UTF-8"?>2.<!DOCTYPE hibernate-configuration PUBLIC3."-//Hibernate/Hibernate Configuration DTD 3.0//EN"4."/hibernate-configuration-3.0.dtd">5.<hibernate-configuration>6.7.<session-factory>8.<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>9.<property name="ername">username</pr operty>10.<property name="connection.password">password</ property>11.<!-- 数据库JDBC驱动类名 -->12.<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>13.<!-- 数据库方言 -->14.<property name="dialect">org.hibernate.dialect.Oracl e10gDialect</property>15.<!-- ddl语句自动建表 -->16.<property name="hbm2ddl.auto">none</property>17.<property name="show_sql">true</property>18.<property name="format_sql">true</property>19.20.<!-- 连接池配置 -->21.<property name="hibernate.connection.provider_clas s">.hibernate.service.jdbc.connections.internal.C3P0C onnectionProvider23.</property>24.<!-- 连接池中JDBC连接的最小数量。
Hibernate配置EhCache缓存之annotation注解
Hibernate配置EhCache缓存之annotation注解ms注解是种流行,越来越多的注解,越来越多的零配置1. 首先设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:2. 在Hibernate配置文件中设置:此外,可以把e_second_level_cache设置为false关闭所有的hibernate二级缓存。
但此属性对指定<cache>的类缺省为true。
3. 为了使用二级缓存,需要在每一个Hibernate Entity上配置。
(1) usage: 提供缓存对象的事务隔离机制,可选值有以下几种(NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)ehcache不支持transactional,其他三种可以支持。
read-only:无需修改,那么就可以对其进行只读缓存,注意,在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不会发生作用。
另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。
read-write:需要更新数据,那么使用读/写缓存比较合适,前提:数据库不可以为serializable transaction isolation level (序列化事务隔离级别)nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。
(2) region (optional): 指定缓存的区域,默认是类的全限定名。
利用缓存区域,可以更精确的指定每个区域的缓存超前策略。
如果指定了缓存区域前缀(在hibernate.cfg.xml中设置cache.region_prefix属性为一个字符串),则所有的缓存区域名前将加上这个前缀。
J2EE项目实训Hibernate框架技术——第3章 Hibernate框架的系统配置文件(第2部分)
第三章Hibernate框架的系统配置文件(第2/2部分)1.1以编程的方式实现Hibernate数据库连接的系统配置1.1.1主要涉及的Hibernate API中的类与接口在应用Hibernate框架时,开发者不仅可以通过前面所介绍的hibernate.cfg.xml文件来向Hibernate框架提供数据库连接相关的各个配置参数,而且也可以通过下面所介绍的编程的方式来达到相同的应用效果。
但为了能够使应用系统达到更好的灵活性,在实际应用系统的开发中,一般都采用前面介绍的hibernate.cfg.xml文件的方式。
1、Configuration类及其作用一个org.hibernate.cfg.Configuration类的对象实例代表了一个应用程序中Java类型到SQL数据库表映射的完整的各个配置的集合,Configuration类被用来构建一个SessionFactory对象,而实体类的映射定义则由不同的XML映射定义文件来提供。
2、在Configuration对象中指定XML映射定义文件可以直接实例化Configuration类来获取一个实例,并为它指定XML映射定义文件,如果映射定义文件在类路径(classpath)中, 则使用addResource()方法。
请见下面的【例3-5】中的代码示例。
【例3-5】在Configuration对象中指定XML映射定义文件的代码示例Configuration hibernateConfiguration=new Configuration();hibernateConfiguration.addResource("Person.hbm.xml");hibernateConfiguration.addResource("Cat.hbm.xml");注意:此时的*.xml文件的存放位置应该为Web应用系统的\WEB-INF\classes目录下。
J2EE项目实训Hibernate框架技术——第3章 Hibernate框架的系统配置文件(第1部分)
第三章Hibernate框架的系统配置文件(第1/2部分)Hibernate框架为了能够在各种不同物理数据库环境下都能够很好地工作, 因此存在着对数据库进行连接的各种配置参数,这些配置参数将集中放在一个文件,如hibernate.cfg.xml文件中。
同时,为了能够实现O/R Mapping功能,也需要针对数据库表和Java中的持久类提供映射的配置文件,如*.hbm.xml文件中。
最后,为了能够提高在应用Hibernate框架时系统的数据访问性能,一般都会应用Hibernate框架中的各种形式的缓存技术,特别是Hibernate框架中所支持的查询缓存及实现。
此时开发者也需要进行相关的与缓存技术实现相关的XML配置文件的设置,如ehcache.xml等。
因此,在应用Hibernate框架时,一般都经常会涉及到下面的三种类型的XML配置文件。
(1)数据库连接的配置文件,如hibernate.cfg.xml文件(2)O/R Mapping的配置文件,如*.hbm.xml文件(3)查询缓存实现的配置文件,如ehcache.xml文件在本章将主要介绍前面两种形式的XML的配置文件的具体应用方法,而对于查询缓存的配置文件将留到后面的第十章“Hibernate框架中的缓存技术”中进行介绍。
1.1Hibernate框架的系统配置文件1.1.1Hibernate框架系统的数据库连接配置1、Hibernate框架系统的配置模板文件由于hibernate.cfg.xml文件中有许多的配置项目,这对初学者而言可能会有一定的难度。
但幸运的是,这些配置文件中的多数配置参数都有比较直观的默认值, 并且随Hibernate框架系统包一同分发的文件中也包括各种配置的模板文件。
读者可以参考位于Hibernate框架系统包下的etc目录中各个模板文件,只需要对这些模板文件进行修改和扩展各种配置选项,就可以满足自己的应用系统的要求。
请见下面的图3.1所示。
Hibernate完整文档
认识Hibernate的基本组件
实体类 实体类映射文件 Hibernate配置文件 辅助工具
Configuration
Configuration 类负责管理Hibernate 的配置信息。它包括如 下内容:
Hibernate运行的底层信息:数据库的URL、用户名、密码、JDBC驱动 类,数据库Dialect,数据库连接池等 Hibernate映射文件(*.hbm.xml)
创建持久化类 User.java
public class User { private long userId; private String userName; private String password; ….. }
Hibernate体验
创建类的映射文件 – User.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="er“ table="T_User"> <id name="userId" type="long" column="User_ID"> <generator class=“identity"/> </id> <property name="userName" type=“string" column="User_Name"/> <property name="password" type=“string" column="Password"/> </class> </hibernate-mapping>
hibernate注解简介
@Entity
@Table(name="T_MODEL_PLANE")
public class ModelPlane {
private Long id;
private String name;
@Id
@Column(name="PLANE_ID")
传统上,Hibernate的配置依赖于外部 XML 文件:数据库映射被定义为一组 XML 映射文件,并且在启动时进行加载。创建这些映射有很多方法,可以从已有数据库模式或Java类模型中自动创建,也可以手工创建。无论如何,您最终将获得大量的 Hibernate 映射文件。此外,还可以使用工具,通过javadoc样式的注释生成映射文件,尽管这样会给您的构建过程增加一个步骤。
...
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
【价值管理】最有价值的hibernate配置文件
经典hibernate配置详解2008-09-09 20:29:29标签:Hibernate配置JA V A框架<meta>元素的属性属性描述class-description 指定描述类的javaDocfield-description 指定描述类的属性javaDocinterface 如果为true,表明生成接口而非类,默认false implements 指定类所实现的接口extends 指定继承的父类名generated-class 重新指定生成的类名scope-class 指定类的修饰符,默认publicscope-set 指定set方法的修饰符,默认publicscope-get 指定get方法的修饰符,默认publicscope-field 指定类的属性的修饰符,默认privateuse-in-toString 如果为true,表示在toString()方法中包含此属性gen-property 如果为false,不会在java类中生成此属性,默认true finder-method 指定find方法名<column>元素属性name 设定字段名字length 设定字段长度not-null 如为true,指名该字段不允许为null,默认falseunique 如为true,指名该字段具有唯一约束,默认falseindex 给一个或多个字段建立索引unique-key 为多个字段设定唯一约束foreign-key 为外键约束命名,在<many-to-many><one-to-one><key><many-to-one>元素中包含foreign-key属性,在双向关联中,inverse属性为true的一端不能设置foreign-keysql-type 设定字段sql类型check 设定sql检查约束用于控制insert or update 语句的映射属性<property>元素的insert属性如为false,在insert中不包含该字段,默认为true<property>元素的update属性如为false,在update中不包含该字段,默认为true<class>元素的mutable属性如为false,等价于所有字段的update属性为false,默认为true<property>元素的dunameic-insert属性如为true,表明动态生成insert语句,只有不为null,才会包含insert语句中,默认false<property>元素的dunameic-update属性如为true,表明动态生成update语句,只有不为null,才会包含insert语句中,默认false<class>元素的dunameic-insert属性如为true,表明等价于所有字段动态生成insert语句,只有不为null,才会包含insert语句中,默认false<class>元素的dunameic-update属性如为true,表明等价于所有字段动态生成update语句,只有不为null,才会包含insert语句中,默认falseHibernate提供的内置标识符生成器increment 适用于代理主键,自动递增,增1(只能是long,int,short)identity 适用于代理主键,底层数据库自动增长字段类型(数据库需支持,只能是long,int,short)(oralce)sequence 适用于代理主键,根据底层数据库的序列来生成标识符(数据库支持序列,只能是long,int,short)hilo 适用于代理主键,根据high/low算法来生成.Hibernate把特定表的字段作为high 值,在默认情况下选用hibernate_unique_key表的next_hi字段(mysql,mssql)native 适用于代理主键,根据数据库自动生成标识符支持能力,来选择identity,sequence,hilouuid.hex 适用于代理主键,采用128位UUID(universal unique identification)算法来生成标识.此算法能在网络环境中生成唯一的字符串标识符,(不建议使用,字符串类型比整形类型的主键占用更多的空间)assigned 适用于自然主键,由java程序负责生成.<hibernate-mapping><class name="项目路径" table="库中对应表名" schema="dbo" catalog="netoa"><meta attribute="class-description">指定描述类的javaDoc</meta><meta attribute="class-scope">指名类的修饰类型</meta><meta attribute="extends">指定继承类</meta><id name="bgrkbh" type="long"><column name="BGRKBH" precision="15" scale="0" sql-type="库中类型" check="BGRKBH>10"/><meta attribute="scope-set">指定类,类属性的getxxx(),setxxx()方法的修饰符包括:static,final,abstract,public,protected,private</meta><generator class="assigned" /></id><property name="Class." type="long"><column name="YSLX" precision="精度" scale="刻度" not-null="默认false" sql-type="数据库中类型"/>附加属性不会影响Hibernate的运行行为<meta attribute="field-description">指定描述类的javaDoc</meta>指定描述类属性的javaDoc</property></class></hibernate-mapping>注意:1 Session的commit()和flush()方法的区别,flush()方法进行清理缓存的操作,执行一系列的SQL语句,但不会提交事务;commit()方法会先调用flush(),然后提交事务.提交事务意味着对数据库所作的更新被永久保存下来.2 Session的setFlushMode()方法用于设定清理缓存的时间点.FlushMode类定义了三种不同的清理模式清理缓存的模式Session的查询方法Session的commit()方法Session的flush()方法FlushMode.AUTO 清理清理清理MIT 不清理清理清理FlushMode.NEVER 不清理不清理清理3 Hibernate应用中java对象的状态临时状态(transient):刚刚用new语句创建,还没被持久化,不处与Session的缓存中,处于临时状态的java对象被称为临时对象.持久化状态(persistent):已经被持久化,加入session的缓存中.处于持久化状态的java 对象被称为持久化对象.游离状态(detached):已经被持久化,但不在处于session的缓存中.处于游离状态的java 对象被称为游离对象.(注意:::::)持久化类与持久化对象是不同的概念.持久化类的实例可以处于临时状态,持久化状态和游离状态.其中处于持久化状态的实例被称为持久化状态.临时对象的特性:1 不处于缓存中,也可以说,不被任何一个Session实例关联2 在数据中没有对应的纪录.在此情况下,java对象进入临时状态1 当通过new创建一个对象时,此时不和数据库中的任何纪录的ex:对象的状态转化过程程序代码对象的生命周期对象的状态tx=session.beginTransaction();Object obj=new Object("tow",new HashSet()); 开始生命周期临时状态session.save(obj); 处于生命周期转化为持久状态Long id=obj.getId();obj=null;Object obj2=(Object)session.load(Object.class,id); 处于生命周期处于持久化状态mit();session.close(); 处于生命周期转变成游离状态System.out.print(obj2.getName()); 处于生命周期处于游离状态obj2=null; 结束生命周期结束生命周期4 cascade属性cascade属性值描述none 在保存更新时,忽略其他关联对象,他是cascade默认属性save-update 当通过Session的save(),update()以及saveOrUpdate()方法来保存或更新当前对象时,及联保存所有关联的新建的临时对象,并且及联更新所有关联的游离对象delete 当通过session的delete()方法删除当前对象时,及联删除所有对象all 包含save-update及delete行为,此外对当前对象执行evict()或lock()操作时,也会对所有关联的持久化对象执行evict()或lock()操作delete-orphan 删除所有和当前对象解除关联关系的对象all-delete-orphan 包含all和delete-orphan5 Hibernate映射类型,对应的java基本类型及对应的标准SQL类型Hibernate 映射类型java类型标准SQL类型integer或者int int INTEGERlong long BIGINTshort short SMALLINTbyte byte TINYINTfloat float FLOATdouble double DOUBLEbig_decimal java.math.BigDecimal NUMERICcharacter char and string CHARstring string V ARCHARboolean boolean BITHibernate映射类型,对应的java时间和日期类型及对应的标准SQL类型映射类型java类型标准SQL类型描述date java.util.Date或者java.sql.Date DATE 代表日期,YYYY-MM-DDtime java.util.Date或者java.sql.Date TIME 代表时间,形式为HH:MM:SS timestamp java.util.Date或者java.sql.Timestamp TIMESTAMP 代表日期和时间,YYYYMMDDHHMMSScalendar java.util.Calendar TIMESTAMP 同上calendar_date java.util.Calendar DATE 代表日期,YYYY-MM-DD。
HibernateValidation中文
HibernateValidation中文Hibernate Validation 中文Hibernate 验证器文档前言:Annotations 是为域对象指定一个不变约束的便利而优雅的途径.例如通过它,你可以表示一个属性不应该是Null值,账户余额绝对不能是负值,等等。
这些域模型的约束通过注释它的属性声明在bean自身。
验证器可以读取这些注释并检查约束违反性。
验证机制可以在没有重复这些规则的情况下在应用程序的不同层里执行(表示层,数据访问层).Hibernate验证器在遵循DRY规则的情况下设计.Hibernate 验证器工作在两个级别。
首先,它能检测位于内存的类实例的约束违反性.其次,它可以把约束应用在hibernate的元模型中并且把它们应用在生成的数据库中.每一个约束注释都与一个为检查实体实例而实现的验证器对应关联。
一个验证器也可以可选的应用约束到hibernate元模型,允许hibernate生成DDL来表达这些约束。
利用合适的事件监听器,你可以通过hibernate在插入或更新的时候检查约束性。
Hibernate验证器没有限定在必须配合hibernate执行验证。
你也可以容易的把它用在其他java的持久化提供者上面(实现了实体监听器).在运行期检查实例时,hibernate验证器把有关违反验证的信息放在一个InvalidValue类型的数组里返回.在其他信息中,InvalidValue所包含的错误描述消息可以嵌入参数值和注释绑定,并且消息字符串可以以资源文件的形式提供.第一章定义约束1.1 什么是约束约束是一个给定的元素(可以使field,property,或bean)所必须遵循的规则.规则的语义可以由注释表达。
约束通常有一些属性用来参数化约束限制。
这些约束应用到被注释的元素。
1.2 内建约束与Hibernate 验证器一起内建了一些约束,他们已经覆盖了大多数基本的数据检查,当然我们后来会看到,你不一定使用它们,你可以在一分钟内写出你自己的约束。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Hibernate Annotations参考文档3.2.0 CR1目录前言1. 翻译说明2. 版权声明前言1. 创建一个注解项目1.1. 系统需求1.2. 系统配置2. 实体Bean2.1. 简介2.2. 用EJB3注解进行映射2.2.1. 声明实体bean2.2.1.1. 定义表(Table)2.2.1.2. 乐观锁定版本控制2.2.2. 映射简单属性2.2.2.1. 声明基本的属性映射2.2.2.2. 声明列属性2.2.2.3. 嵌入式对象(又名组件)2.2.2.4. 无注解之属性的默认值2.2.. 映射主键属性2.2.4. 映射继承关系2.2.4.1. 每个类一张表2.2.4.2. 每个类层次结构一张表2.2.4.3. 连接的子类2.2.4.4. 从父类继承的属性2.2.5. 映射实体Bean的关联关系2.2.5.1. 一对一(One-to-one)2.2.5.2. 多对一(Many-to-one)2.2.5.3. 集合类型2.2.5.4. 用cascading实现传播性持久化(Transitive persistence)2.2.5.5. 关联关系获取2.2.6. 映射复合主键与外键2.2.7. 映射二级表(secondary tables)2.3. 映射查询2.3.1. 映射EJBQL/HQL查询2.3.2. 映射本地化查询2.4. Hibernate独有的注解扩展2.4.1. 实体2.4.2. 标识符2.4.3. 属性2.4.3.1. 访问类型2.4.3.2. 公式2.4.3.3. 类型2.4.3.4. 索引2.4.3.5. @Parent2.4.3.6. 生成的属性2.4.4. 继承2.4.5. 关于单个关联关系的注解2.4.5.1. 延迟选项和获取模式2.4.6. 关于集合类型的注解2.4.6.1. 参数注解2.4.6.2. 更多的集合类型2.4.7. 缓存2.4.8. 过滤器2.4.9. 查询3. 通过XML覆写元数据3.1. 原则3.1.1. 全局级别的元数据3.1.2. 实体级别的元数据3.1.3. 属性级别的元数据3.1.4. 关联级别的元数据4. Hibernate验证器4.1. 约束4.1.1. 什么是约束?4.1.2. 内建约束4.1.3. 错误信息4.1.4. 编写你自己的约束4.1.5. 注解你的领域模型4.2. 使用验证器框架4.2.1. 数据库schema层次验证4.2.2. Hibernate基于事件的验证4.2.3. 程序级验证4.2.4. 验证信息5. Hibernate与Lucene集成5.1. 使用Lucene为实体建立索引5.1.1. 注解领域模型5.1.2. 启用自动索引A. 术语表前言WARNING! This is a translated version of the English Hibernate reference documentation. The translated version might not be up to date! However, the differences should only be very minor. Consult the English reference documentation if you are missing information or encounter a translation error. If you like to contribute to a particular translation, contact us on the Hibernate developer mailing list.Translator(s): RedSaga Translate Team 满江红翻译团队 <caoxg@>1. 翻译说明本文档的翻译是在网络上协作进行的,也会不断根据Hibernate 的升级进行更新。
提供此文档的目的是为了减缓学习Hibernate 的坡度,而非代替原文档。
我们建议所有有能力的读者都直接阅读英文原文。
若您对翻译有异议,或发现翻译错误,敬请不吝赐教,报告到如下地址:/confluence/display/HART/Home 表 1. Hibernate Annotation v3翻译团队 关于我们满江红.开源, 从成立之初就致力于Java 开放源代码在中国的传播与发展,与国内多个Java 团体及出版社有深入交流。
坚持少说多做的原则,目前有两个团队,“OpenDoc 团队”与“翻译团队”,本翻译文档即为翻译团队作品。
OpenDoc 团队已经推出包括Hibernate 、iBatis 、Spring 、WebWork 的多份开放文档,并于2005年5月在Hibernate 开放文档基础上扩充成书,出版了原创书籍:《深入浅出Hibernate 》,本书400余页,适合各个层次的Hibernate 用户。
(/hibernate_book.html)敬请支持。
致谢在我们翻译Hibernate Annotation 参考文档的同时,还有一位热心的朋友也在进行着同样序号标题中文标题翻译1审2审--Contents目录Liu Chang #1Setting up an annotations projec创建一个注解项目melthaw Zheng Shuai superq #2Entity Beans-Introduction实体Bean-简介melthaw Zheng Shuai superq #3Entity Beans-Mapping with EJB3 Annotations 实体Bean-用EJB3注解进行映射melthawZheng Shuai superq, Liu Chang, Sean Chan #4Entity Beans-MappingQueries 实体Bean-映射查询melthawZheng Shuai superq, Liu Chang, Sean Chan #5Entity Beans-Hibernate Annotation Extensions 实体Bean-Hibernate 独有的注解扩展Sean Chan morning melthaw#6Overriding metadata through XML通过XML 覆写元数据icessmelthaw Sean Chan #7Hibernate Validator Hibernate 验证器DigitalSonic morningmelthaw #8Hibernate LuceneIntegrationHibernate 与Lucene集成mochowmorning melthaw #9Appendix:Glossary 附录:术语表mochowLiu Chang曹晓钢的工作,这位朋友就是icess(冰雨),由icess翻译的中文版的地址:/hibernate/a/ref/index.htm2. 版权声明Hibernate英文文档属于Hibernate发行包的一部分,遵循LGPL协议。
本翻译版本同样遵循LGPL协议。
参与翻译的译者一致同意放弃除署名权外对本翻译版本的其它权利要求。
您可以自由链接、下载、传播此文档,或者放置在您的网站上,甚至作为产品的一部分发行。
但前提是必须保证全文完整转载,包括完整的版权信息和作译者声明,并不能违反LGPL 协议。
这里“完整”的含义是,不能进行任何删除/增添/注解。
若有删除/增添/注解,必须逐段明确声明那些部分并非本文档的一部分。
前言正如其他的ORM工具,Hibernate同样需要元数据来控制在不同数据表达形式之间的转化. 在Hibernate 2.x里,多数情况下表示映射关系的元数据保存在XML文本文件中. 还有一种方式就是Xdoclet,它可以在编译时利用Javadoc中的源码注释信息来进行预处理. 现在新的JDK标准(JDK1.5以上)也支持类似的注解功能,但相比之下很多工具对此提供了更强大更好用的支持. 以IntelliJ IDEA和Eclipse为例,这些IDE工具为JDK 5.0注解功能提供了自动完成和语法高亮功能. 注解被直接编译到字节码里,并 在运行时(对于Hibernate来讲就是启动的时候)通过反射读取这些注解, 因此外部XML文件就不再需要了.EJB3规范最终认可了透明化ORM的成功范例以及市场对于这种技术的兴趣. EJB3规范标准化了ORM的基础API而且在任何ORM持久化机制中使用元数据. Hibernate EntityManager实现了EJB3持久化规范中定义的编程接口和生命周期规则. 在Hibernate Core的基础上再结合 Hibernate Annotations就实现了一套完整(并且独立)的EJB3持久化解决方案. 你可以结合三者来使用,也可以抛开EJB3编程接口和生命周期规则而独立使用注解, 甚至只单独使用Hibernate Core. 这些都取决于项目的商业和技术上的实际需求. Hibernate允许你直接使用native APIs,如果有需要, 甚至可以直接操作JDBC和SQL.注意本文档基于Hibernate Annotations的预览版(遵从EJB 3.0/JSR-220最终草案). 这个版本和新规范中定义的最终概念已经非常接近了.我们的目标是提供一套完整的ORM注解, 包括EJB3的标准注解以及Hibernate3的扩展(后者是EJB3规范中没有涉及到的). 最终通过注解你可以完成任何可能的映射.详情参考???.EJB3最终草案修改了部分注解, /371.html提供了从上一个版本到最新版本的迁移指南.第 1 章创建一个注解项目1.1. 系统需求首先从Hibernate官方网站下载并解压Hibernate Annotations的发布包。
这个版本(预览版)要求使用Hibernate 3.2.0.CR2或更高版本。
请不要和老版本的Hibernate 3.x混合起来使用。
这个版本在Hibernate core 3.2.0.CR2的基础上工作良好。
首先确定你已经安装了JDK 5.0。
当然就算使用低版本的JDK, Xdoclet也可以提供(基于注解的)元数据所带来的部分功能。
不过请注意本文档只描述跟JDK5.0注解有关的内容,关于Xdoclet请参考相关文档。
1.2. 系统配置首先就是设置classpath(当然是在IDE中创建了一个新项目之后)。
将Hibernate3核心文件以及其依赖的第三方库文件(请参考lib/README.txt文件)加入到你的classpath里面。