中文版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的升级进行更新。
- 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里面。