1、Hibernate 注释大全Hibernate 注释大全 2(2010-01-16 14:28:05)转载标签:it 一对多OneToMany 注解可定义一对多关联。一对多关联可以是双向的。双向规范中多对一端几乎总是双向关联中的主体(owner)端,而一对多的关联注解为 OneToMany(mappedBy=)Entitypublic class Troop OneToMany(mappedBy=“troop“)public Set getSoldiers() .Entitypublic class Soldier ManyToOneJoinColumn(name=“troop_fk“)pub
2、lic Troop getTroop() .Troop 通过 troop 属性和 Soldier 建立了一对多的双向关联。在 mappedBy 端不必也不能定义任何物理映射。单向本文来自 CSDN 博客,转载请标明出处:http:/ class Customer implements Serializable OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)JoinColumn(name=“CUST_ID“)public Set getTickets() .Entitypublic class Ticket implements
3、 Serializable . /no bidir一般通过连接表来实现这种关联,可以通过JoinColumn 注解来描述这种单向关联关系。上例 Customer 通过 CUST_ID 列和 Ticket 建立了单向关联关系。通过关联表来处理单向关联Entitypublic class Trainer OneToManyJoinTable(name=“TrainedMonkeys“,joinColumns = JoinColumn( name=“trainer_id“),inverseJoinColumns = JoinColumn( name=“monkey_id“)public Set ge
4、tTrainedMonkeys() .Entitypublic class Monkey . /no bidir通过关联表来处理单向一对多关系是首选,这种关联通过 JoinTable 注解来进行描述。上例子中 Trainer 通过TrainedMonkeys 表和 Monkey 建立了单向关联关系。其中外键trainer_id 关联到 Trainer(joinColumns)而外键 monkey_id 关联到Monkey(inverseJoinColumns).默认处理机制通过连接表来建立单向一对多关联不需要描述任何物理映射,表名由一下 3 个部分组成,主表(owner table)表名 +
5、下划线 + 从表(the other side table)表名。指向主表的外键名:主表表名+下划线+主表主键列名指向从表的外键定义为唯一约束,用来表示一对多的关联关系。Entitypublic class Trainer OneToManypublic Set getTrainedTigers() .Entitypublic class Tiger . /no bidir上述例子中 Trainer 和 Tiger 通过 Trainer_Tiger 连接表建立单向关联关系。其中外键 trainer_id 关联到 Trainer 表,而外键 trainedTigers_id 关联到 Tiger
6、表。多对多通过 ManyToMany 注解定义多对多关系,同时通过 JoinTable 注解描述关联表和关联条件。其中一端定义为 owner, 另一段定义为 inverse(对关联表进行更新操作,这段被忽略)。Entitypublic class Employer implements Serializable ManyToMany(targetEntity=org.hibernate.test.metadata.manytomany.Employee.class,cascade=CascadeType.PERSIST, CascadeType.MERGE)JoinTable(name=“EM
7、PLOYER_EMPLOYEE“,joinColumns=JoinColumn(name=“EMPER_ID“),inverseJoinColumns=JoinColumn(name=“EMPEE_ID“)public Collection getEmployees() return employees;.Entitypublic class Employee implements Serializable ManyToMany(cascade = CascadeType.PERSIST, CascadeType.MERGE,mappedBy = “employees“,targetEntit
8、y = Employer.class)public Collection getEmployers() return employers;默认值:关联表名:主表表名 + 下划线 + 从表表名;关联表到主表的外键:主表表名 + 下划线 + 主表中主键列名;关联表到从表的外键名:主表中用于关联的属性名 + 下划线 + 从表的主键列名。用 cascading 实现传播持久化(Transitive persistence)cascade 属性接受值为 CascadeType 数组,其类型如下:? CascadeType.PERSIST: cascades the persist (create) op
9、eration to associated entities persist() is called or if the entity is managed 如果一个实体是受管状态,或者当 persist() 函数被调用时,触发级联创建(create)操作。? CascadeType.MERGE: cascades the merge operation to associated entities if merge() is called or if the entity is managed 如果一个实体是受管状态,或者当 merge() 函数被调用时,触发级联合并(merge)操作。?
10、CascadeType.REMOVE: cascades the remove operation to associated entities if delete() is called 当 delete() 函数被调用时,触发级联删除(remove)操作。? CascadeType.REFRESH: cascades the refresh operation to associated entities if refresh() is called 当 refresh() 函数被调用时,出发级联更新(refresh)操作。? CascadeType.ALL: all of the abo
11、ve 以上全部映射二级列表使用类一级的 SecondaryTable 和 SecondaryTables 注解可以实现单个实体到多个表的映射。使用 Column 或者 JoinColumn 注解中的 table 参数可以指定某个列所属的特定表。EntityTable(name=“MainCat“)SecondaryTables(SecondaryTable(name=“Cat1“, pkJoinColumns=PrimaryKeyJoinColumn(name=“cat_id“, referencedColumnName=“id“),SecondaryTable(name=“Cat2“, un
12、iqueConstraints=UniqueConstraint(columnNames=“storyPart2“)public class Cat implements Serializable private Integer id;private String name;private String storyPart1;private String storyPart2;Id GeneratedValuepublic Integer getId() return id;public String getName() return name;Column(table=“Cat1“)publ
13、ic String getStoryPart1() return storyPart1;Column(table=“Cat2“)public String getStoryPart2() return storyPart2;上述例子中, name 保存在 MainCat 表中,storyPart1 保存在 Cat1 表中,storyPart2 保存在 Cat2 表中。 Cat1 表通过外键 cat_id 和 MainCat 表关联, Cat2 表通过 id 列和 MainCat 表关联。对 storyPart2 列还定义了唯一约束。映射查询使用注解可以映射 EJBQL/HQL 查询,Named
14、Query 和 NamedQueries 是可以使用在类级别或者 JPA 的 XML 文件中的注解。select p from Plane p.EntityNamedQuery(name=“night.moreRecentThan“, query=“select n from Night n where n.date = :date“)public class Night .public class MyDao doStuff() Query q = s.getNamedQuery(“night.moreRecentThan“);q.setDate( “date“, aMonthAgo );L
15、ist results = q.list();.可以通过定义 QueryHint 数组的 hints 属性为查询提供一些 hint 信息。下图是一些 Hibernate hints:映射本地化查询通过SqlResultSetMapping 注解来描述 SQL 的 resultset 结构。如果定义多个结果集映射,则用 SqlResultSetMappings。NamedNativeQuery(name=“nightprivate String model;private double speed;Idpublic String getName() return name;public void
16、 setName(String name) this.name = name;Column(name=“model_txt“)public String getModel() return model;public void setModel(String model) this.model = model;public double getSpeed() return speed;public void setSpeed(double speed) this.speed = speed;上例中 model1 属性绑定到 model_txt 列,如果和相关实体关联设计到组合主键,那么应该使用
17、FieldResult 注解来定义每个外键列。FieldResult 的名字组成:定义这种关系的属性名字 + “.“ + 主键名或主键列或主键属性。EntitySqlResultSetMapping(name=“compositekey“,entities=EntityResult(entityClass=org.hibernate.test.annotations.query.SpaceShip.class,fields = FieldResult(name=“name“, column = “name“),FieldResult(name=“model“, column = “model“
18、),FieldResult(name=“speed“, column = “speed“),FieldResult(name=“captain.firstname“, column = “firstn“),FieldResult(name=“captain.lastname“, column = “lastn“),FieldResult(name=“dimensions.length“, column = “length“),FieldResult(name=“dimensions.width“, column = “width“),columns = ColumnResult(name =
19、“surface“),ColumnResult(name = “volume“) )NamedNativeQuery(name=“compositekey“,query=“select name, model, speed, lname as lastn, fname as firstn, length, width, length * width as resultSetMapping=“compositekey“)如果查询返回的是单个实体,或者打算用系统默认的映射,这种情况下可以不使用 resultSetMapping,而使用 resultClass 属性,例如:NamedNativeQu
20、ery(name=“implicitSample“, query=“select * from SpaceShip“,resultClass=SpaceShip.class)public class SpaceShip Hibernate 独有的注解扩展Hibernate 提供了与其自身特性想吻合的注解,org.hibernate.annotations package 包含了这些注解。实体org.hibernate.annotations.Entity 定义了 Hibernate 实体需要的信息。? mutable: whether this entity is mutable or not
21、 此实体是否可变? dynamicInsert: allow dynamic SQL for inserts 用动态 SQL新增? dynamicUpdate: allow dynamic SQL for updates 用动态 SQL更新? selectBeforeUpdate: Specifies that Hibernate should never perform an SQL UPDATE unless it is certain that an object is actually modified.指明 Hibernate 从不运行 SQL Update,除非能确定对象已经被修改
22、? polymorphism: whether the entity polymorphism is of PolymorphismType.IMPLICIT (default) or PolymorphismType.EXPLICIT 指出实体多态是 PolymorphismType.IMPLICIT(默认)还是PolymorphismType.EXPLICIT? optimisticLock: optimistic locking strategy (OptimisticLockType.VERSION, OptimisticLockType.NONE, OptimisticLockTyp
23、e.DIRTY or OptimisticLockType.ALL) 乐观锁策略标识符org.hibernate.annotations.GenericGenerator 和org.hibernate.annotations.GenericGenerators 允许你定义hibernate 特有的标识符。Id GeneratedValue(generator=“system-uuid“)GenericGenerator(name=“system-uuid“, strategy = “uuid“)public String getId() Id GeneratedValue(generator=
24、“hibseq“)GenericGenerator(name=“hibseq“, strategy = “seqhilo“,parameters = Parameter(name=“max_lo“, value = “5“),Parameter(name=“sequence“, value=“heybabyhey“)public Integer getId() 新例子GenericGenerators(GenericGenerator(name=“hibseq“,strategy = “seqhilo“,parameters = Parameter(name=“max_lo“, value =
25、 “5“),Parameter(name=“sequence“, value=“heybabyhey“),GenericGenerator(.)自然 ID用 NaturalId 注解标识公式让数据库而不是 JVM 进行计算。Formula(“obj_length * obj_height * obj_width“)public long getObjectVolume()索引通过在列属性(property)上使用Index 注解,可以指定特定列的索引,columnNames 属性(attribute)将随之被忽略。Column(secondaryTable=“Cat1“)Index(name=
26、“story1index“)public String getStoryPart1() return storyPart1;辨别符EntityDiscriminatorFormula(“case when forest_type is null then 0 else forest_type end“)public class Forest . 过滤 查询 .? 其中一个实体通过外键关联到另一个实体的主键。注:一对一,则外键必须为唯一约束。Entitypublic class Customer implements Serializable OneToOne(cascade = Cascade
27、Type.ALL)JoinColumn(name=“passport_fk“)public Passport getPassport() .Entitypublic class Passport implements Serializable OneToOne(mappedBy = “passport“)public Customer getOwner() .通过JoinColumn 注解定义一对一的关联关系。如果没有JoinColumn 注解,则系统自动处理,在主表中将创建连接列,列名为:主题的关联属性名 + 下划线 + 被关联端的主键列名。上例为 passport_id, 因为 Custo
28、mer 中关联属性为 passport, Passport 的主键为 id.? 通过关联表来保存两个实体之间的关联关系。注:一对一,则关联表每个外键都必须是唯一约束。Entitypublic class Customer implements Serializable OneToOne(cascade = CascadeType.ALL)JoinTable(name = “CustomerPassports“,joinColumns = JoinColumn(name=“customer_fk“),inverseJoinColumns = JoinColumn(name=“passport_f
29、k“)public Passport getPassport() .Entity public class Passport implements Serializable OneToOne(mappedBy = “passport“)public Customer getOwner() .Customer 通过 CustomerPassports 关联表和 Passport 关联。该关联表通过 passport_fk 外键指向 Passport 表,该信心定义为 inverseJoinColumns 的属性值。 通过 customer_fk 外键指向 Customer 表,该信息定义为 joinColumns 属性值。