hibernate映射

三种方式:
    持久化注解   目前开发主流方式
    XML配置描述文件(XML deployment descriptor,可以让Hibernate的PO类与JPA实体类兼容,实际中很少用)
    传统的XML映射文件(*.hbm.xml)

映射类
    @Entity
    @Table{
                    name
                    catalog
                    indexes
                    schema
                    uniqueConstraints
                 }
    @Index
    @Proxy
    @DynamicInsert
    @DynamicUpdate
    @SelectBeforeUpdate
    @PolymorphismType
    @Where
    @BatchSize
    @OptimisticLocking
    @Check
    @Subselect

映射属性
    @Column{
                        columnDefinition
                        insertable
                        length
                        name
                        nullable
                        precision
                        scale
                        table
                        unique
                        updatable
                     }
    @Formula{
                        注意:1、value="(sql)"的英文括号不能少
                                  2、如果需要在value属性中使用参数,则直接使用where cur.id =  currencyID形式
                        eg.:@Formula("(select concat(nt.title,nt.content)"+"from news_inf nt where nt.id = id)")
                      }
    @Generated{
                            当Hibernate执行一条insert(当@Generated的value为INSERT或ALWAYS时)
                            或update(当@Generated的value为ALWAYS时)时,Hibernate会立即执行一条
                            select语句来获取该数据列的值,并将该值赋给该持久化对象的该属性。
                            可以和触发器一起使用,生成某个属性的值。
                         }
    @Transient{
                         修饰不想持久保存的属性,生成的sql中不会有这列的插入
                        }
    @Enumerated{
                                修饰枚举类型的属性
                                当其value属性为EnumType.STRING时,底层数据库保存枚举值的名称;
                                当其value属性为EnumType.ORDINAL时,底层数据库保存枚举值的序号;
                            }
    @Lob{    
                  当持久化类的属性为byte[]、Byte[]或java.io.Serializable类型时,@Lob修饰的属性将映射为底层的
                  Blob列;
                  当、、、、、、、、char[]、Character[]或java.lang.String时,、、、、、、、、、、、、、、、、
                  Clob列。
              }
    @Basic在@Lob的基础上加了延迟加载,加载对象时,并不立即加载pic属性,而是加载一个“虚拟”代理。
    @Basic{
                    fetch{
                                FetchType.EAGER 立即加载
                                FetchType.LAZY   延迟加载
                             }
                    optional 是否允许使用null值
                }
    @Temporal{
                           TemporalType.DATE
                           TemporalType.TIME
                           TemporalType.TIMESTAMP
                        }

映射主键
    @GeneratedValue{
                                    strategy{
                                                     GenerationType.AUTO(默认值)
                                                     GenerationType.IDENTITY
                                                     GenerationType.SEQUENCE(要与 @SequenceGenerator一起使用)
                                                     GenerationType.TABLE(要与@TableGenerator一起使用)
                                                  }
                                    generator   指定@SequenceGenerator或@TableGenerator的名称                                
                                   }
    @SequenceGenerator{
                                            name
                                            allocationSize
                                            catalog
                                            schema
                                            initialValue
                                            sequenceName
                                        }
    
  @TableGenerator
                                    name
                                    allocationSize
                                    catalog
                                    schema
                                    initialValue
                                    sequenceName
                                eg.:
                                       @TableGenerator(name="newsGen" ,           
                                        table="NEWS_ID_GEN",pkColumnName="gen_key",
                                        valueColumnName="gen_value",
                                        pkColumnValue="news_id"
                                        )
                                        @GeneratedValue(strategy=GenerationType.TABLE ,
                                         generator="newsGen")
                                }      
 
Hibernate主键生成策略    
    使用@GenericGenerator来使用Hibernate提供的主键生成策略
    @GenericGenerator{
                                        name
                                        strategy{
                                                        increment
                                                        identity
                                                        sequence
                                                        hilo
                                                        seqhilo
                                                        uuid
                                                        guid
                                                        native
                                                        assigned
                                                        select
                                                        foreign
                                                      }
                                     }

映射集合属性
注意:要求持久化集合字段必须声明为接口,两个持久化对象不能共享同一个集合元素的引用
映射集合属性 
@ElementCollection{
                                        fetch
                                        targetClass    
                                  }
 
映射集合属性表
@CollectionTable{
                                  name
                                  catalog
                                  schema
                                  indexes
                                  joinColumns
                                  uniqueConstraints
                             }
 
@JoinColumn{
                              columnDefinition
                              name
                              insertable
                              updatable
                              nullable
                              table
                              unique
                              referencedColumnName
                       }
 
@Column
 
索引列
@OrderColumn
@MapKeyColumn
 
    List集合属性
        示例代码:
            // 集合属性,保留该对象关联的学校
            @ElementCollection(targetClass=String.class)
            // 映射保存集合属性的表
            @CollectionTable(name="school_inf",
                        joinColumns=@JoinColumn(name="person_id",nullable=false))
 
            // 指定保存集合元素的列为 school_name
            @Column(name="school_name")
            // 映射集合元素索引的列
            @OrderColumn(name="list_order")
        private List<String> schools = new ArrayList<>();
    
    数组几乎与List集合一样
 
    Set集合属性   
           没有索引
     示例代码:
         @ElementCollection(targetClass=String.class)
           // 映射保存集合属性的表
          @CollectionTable(name="school_inf",
                         joinColumns=@JoinColumn(name="person_id",nullable=false))
 
          // 指定保存集合元素的列为 school_name
         @Column(name="school_name",
                nullable=false)
          private Set<String> schools = new HashSet<>();
 
Map集合属性
      索引列用@MapKeyColumn映射
   示例代码:
        // 集合属性,保留该对象关联的成绩
            @ElementCollection(targetClass=Float.class)
            // 映射保存集合属性的表
            @CollectionTable(name="score_inf",
                        joinColumns=@JoinColumn(name="person_id",nullable=false))
            @MapKeyColumn(name="subject_name")
            //指定Map key的类型为String
            @MapKeyClass(String.class)
            // 指定保存集合元素的列为 school_name
            @Column(name="mark")
        private Map<String , Float> score = new HashMap<>();
 
有序集合映射(SortedSet、SortedMap)
   @SortNatural 
   @SortComparator
   @OrderBy
    示例代码:
    // 有序集合属性
        @ElementCollection(targetClass=String.class)
        // 映射保存集合元素的表
        @CollectionTable(name="training_inf",
        joinColumns=@JoinColumn(name="person_id" , nullable=false))
        // 定义保存集合元素的数据列
        @Column(name="training_name" , nullable=false)
        // 使用@SortNatural指定使用自然排序
        @SortNatural
        private SortedSet<String> trainings
            = new TreeSet<>();

映射数据库对象
    两种方式:1、在映射文件中显示声明create和drop命令
                     2、提供一个实现了org.hibernate.mapping.AuxiliaryDatabaseObject的类,这个类知道如何组织create和drop命令。
                注:为让Hibernate根据<database-object../>创建数据表,要将Hibernate配置文件里的hbm2ddl.auto属性值改成create
    1:<hibernate-mapping>
                ...... 
               <database-object>
                    <create>create trigger tri ...</create>
                    <drop>create trigger tri</drop>
               </database-object>
          </hibernate-mapping>
 
    2:<hibernate-mapping>
                ...... 
               <database-object>
                    <definition class="MyTriggerDefinition"/> 
               </database-object>
          </hibernate-mapping>
   3、指定某些数据库对象仅在特定的方言中才可使用
    3:<hibernate-mapping>
                ...... 
               <database-object>
                    <create>create table test(t_name varchar(255));</create>
                    <drop></drop>
                    <dialect-scope name="org.hibernate.dialect.MySQL5Dialect" />
                    <dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
               </database-object>
          </hibernate-mapping>
    
SchemaExport工具--->根据映射文件来生成数据库对象(使用这个生成数据库对象时,无须将hbm2ddl.auto属性值改为create,使用update也行)
    Configuration conf = new Configuration().configure();
   //创建SchemaExport对象
    SchemaExport se = new SchemaExport(conf);
   //设置输出格式良好的SQL脚本
    se.setFormat(true)
        //设置保存SQL脚本的文件名
        .setOutputFile("new.sql")
        //输出SQL脚本,并执行
        .create(true,true);
 
也可以直接使用java命令来解释、执行该工具类,命令格式如下:
    java -cp hibernate_classpaths org.hibernate.tool.hbm2ddl.SchemaExport options mapping_files

组件属性
    @Embeddable修饰组件类
    组件类里可以加@parent
原文地址:https://www.cnblogs.com/goingforward/p/5756841.html