文章目录
官网:http://hibernate.org/orm/documentation/5.4/
JPA、hibernate关系:JPA为ORM规范,hibernate实现了JPA。
Getting Started
ORM,Object/Relational Mapping;mapping data between object model representation to relational model representation.
使用方式:SessionFactory/Session、EntityManagerFactory/EntityManager(JPA)
SessionFactory模式
配置文件
https://www.jianshu.com/p/7cf000f92016
<hibernate-configuration>
<session-factory>
<property name="name" value="value"/> 属性
<mapping resource/class=""/> 映射文件,resource加载xml配置,class加载annotation配置
</session-factory>
</hibernate-configuration>
配置文件也可使用properties格式。配置内容:dataSource、mapper
构建SessionFactory
SessionFactory sf = new Configuration().configure().buildSessionFactory();//configure()可指定配置文件位置
Session session = sf.openSession();//
Transaction t = session.beginTransaction();//获取事务
t.commit();//提交事务
EntityManager模式
配置文件
https://blog.youkuaiyun.com/qq_33349750/article/details/75078689
需配置:dataSource、mapper、transacton等
位置:META-INF/persistence.xml。
可配置多个persistence-unit,每个EntityManagerFactor对应一个,name属性。
构建EntityManagerFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory(puName);//name属性
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.getTransaction().commit();
em.close();//关闭
User Guide
https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html
1 Architecture
hibernate实现JPA规范:
- SesseionFactory;继承EntityManagerFactory
- Session;继承EntityManager
- Transaction;继承EntityTransaction
2 Domain Model
resultMap、sql构建
2.1,Mapping types
org.hibernate.type.Type,规定数据映射。
hibernate type:value type(basic、embeddable、collection),entity type。
类比mybatis,basic–property,enbeddable–association,collection–collection,entity type–resultMap
entity type,id唯一。
2.2,Naming strategies
属性映射,两阶段:domain model–logical name,logical name–physical name
2.3,Basic Types
@Basic,标记model属性为basic type。数据库列默认映射为basic type。
@Column,绑定列。columnDefinition,列DDL声明。
@Enumerated,映射枚举类;值:EnumType.ORDINAL(顺序)、EnumType.STRING(名称)
@Lob,映射Blob(Blob、byte[])、Clob(Clob、String、char[])
@Temporal,映射时间,java类型非java.sql包下时使用。
列名为保留字时,字符串内使用双引号括起列名。全局配置:hibernate.globally_quoted_identifiers
@ColumnTransformer,列转换;read、write属性。
@Formula,公式;@Formula(“columnA * 100”)
Generated Properties
三要素:when(GenerationTime),strategy(GenerationType),generator。selectKey标签。
@Generated,标记自动生成属性(basic);值:GenerationTime.NEVER/INSERT/ALWAYS
@GeneratorType,自定义属性生成器;type生成器,when生成器时机(GenerationTime)
@CreationTimestamp/@UpdateTimestamp,标记属性为jvm时间。
@ValueGenerationType,元注解,指定属性生成器。
2.4 Embeddable types
association
2.4.1,Component/Embedded
复用基本类型映射。
@Embeddable标记类,@Column标记属性映射
@Embedded标记属性为embeddable类型
2.4.8,@Target mapping
@Target,标记多态属性实现类型
2.4.9,@Parent mapping
@Parent,关联owner entity。
2.5 Entity types
@Entity–resultMap;默认name属性为类名,不可重复。@Table绑定表。
hibernate懒加载,runtime proxy;基于entity为非final类型。
entity类提供无参构造器;声明getter/setter方法;
标记id属性,属性最好为对象。@Id。
基于id属性,重写equals()、hashCode()方法。id相同时,引用前序对象。
2.6 Identifiers
标记主键,区分entity实例。主键类型最好为对象、包装对象。
特性:UNIQUE、NOT NULL、IMMUTABLE
2.6.1,Simple dentifiers
@Id,标记主键属性。
@GeneratedValue,自动生成主键;JPA自动生成主键时,仅整形id支持移植。
2.6.2,Composite identifiers
JPA
@EmbeddedId;标记主键属性。
@Embeddable,标记主键属性类;类中属性可为:basic、composite、@ManyToOne
@IdClass标记entity类,指定主键类;@Id标记主键类属性
hibernate
@Id,标记主键所有属性。若主键属性非basic类型,需标记@Entity。
2.6.7 Generate identifier values
JPA portably defines identifier value generation just for integer types.
Hibernate支持多种类型。
@GeneratedValue,生成并设置主键;strategy–GenerationType,generator–String
GenerationType
- AUTO;自动确定。UUID–UUID identifier,numerical–自动匹配generator
- SEQUENCE;通过sequence生成;对不支持squence的数据库,使用tableGenerator
- IDENTITY;insert后通过主键策略生成主键;如自增。建议使用SEQUENCE替代。
- TABLE;通过table生成主键;
generator
- @SequenceGenerator;序列主键生成器。属性:name、squenceName序列名
- @TableGenerator;表格生成主键;属性:name、table、pkColumnName/pkColumnValue、valueColumnName
- @GenericGenerator;自定义主键策略。属性:name、strategy(如:native、uuid、increment等)、parameters参数,可指定optimizer(优化策略,none、pooled-lo、pooled、hilo)
@GenericGenerator(
name = "product_generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "product_sequence"),
@Parameter(name = "initial_value", value = "1"),
@Parameter(name = "increment_size", value = "3"),
@Parameter(name = "optimizer", value = "pooled-lo")
}
)
2.6.15,Derived Identifiers
@MapsId,自动推断主键。用于@OneToOne、@ManyToOne
2.6.16,@RowId
@RowId,标记entity类;若数据库支持ROWID,则hibernate可使用其进行crud操作。
2.7 Association
entity间关联,表关联(外键、中间表)。注解前一个One、Many指当前类。
@ManyToOne,关联child、parent。
@OneToMany,关联parent、children。双向时通过mappedBy将外键维护交由Many端。
@OneToOne
@ManyToMany
如未指定关联关系,hibernate自动生成外键、关联表。
@JoinColumn;关联列;name外键列列名(Many)、refrenceColumnName关联列列名(默认主键)。Many端为关系维护端(双向时标记@JoinColumn),负责外键记录更新;关系被维护端无权更新外键记录。
@JoinColumns,多个关联列。
@PrimaryKeyColumn,主键关联。
@JoinTable;关联关系表;name、joinColumns、inverseJoinColumns
@NotFound;关联无匹配时策略;NotFoundAction.EXCEPTION/IGNORE
2.8 Collections
@ElementCollection;注解集合属性;集合元素为value type。
@OrderColumn/@OrderBy;声明collection顺序机制。
hibernate可根据@OneToMany、@ManyToOne自动生成外键或关联表。
2.9 Natural Ids
@NaturalId,标记natural id。mutable=true,默认不可变
api可使用natural id进行查询。
@Immutable,标记entity、collection;表示不可变