Hibernate Annotations 注解
對於org.hibernate.annotations與org.hibernate.persistence,它的注釋比如Columns,可是不知道怎么使用,但是hibernate中也封裝了javax.persistence,而且數據庫映射注釋主要還是使用javax.persistence,即如下注釋元素Column,使用規則如下。

- @Entity 聲明當前是一個持久化類
- @Table 設置當前持久化類所映射的數據庫表,如果當前類中沒有使用@Table注解,Hibernate會自動使用默認的持久化類的類名(不帶包名)作為所映射的表名
- @Id 設置當前持久化類的標示符屬性
- @GeneratedValue 設置當前標示符的生產策略。@GeneratedValue的name屬性設置生成策略的名稱是TABLE、INENTITY、SEQUENCE或者AUTO之一。
- @Column 將持久化類的數學與數據庫表中的字段進行映射,name屬性值為映射的字段名,length屬性值為字段的長度,unique屬性表示該列上設置唯一的約束,nullable屬性設置該列的值是否可以為空,precision實現設置該字段的精度,scale屬性設置該字段的小數位數
- @Transient 標注的屬性進行持久化映射
- @Temporal java中沒有定義時間精度的api,因此處理時間類型數據時,需要設置存儲在數據庫中所預期的精度,使用@Temporal注釋可以調整時間的精度為:DATE、TIME和TIMESTAMP三種
- @ManyToOne 設置該當前持久化類類與其他持久化類之間的多對一關聯,其中CascadeType值表示Hibernate將進行級聯操作
- @OneToMany 設置該當前持久化類與其他持久化類之間的一對多關聯
- @OneToOne 設置該當前持久化類與其他持久化類之間的一對一關聯
- @ManyToMany 設置該當前持久化類與其他持久化類之間的多對多關聯
- @NameQueries 在持久化類中設置命名查詢,參考@NameQuery的使用
- @NameQuery 在持久化類中設置命名查詢,@NamedQuery 和@NamedQueries注釋加在在類和包上。如下面的例子:
- @NamedQueries({@NamedQuery(name="queryById",query="select p from Product p where id=:id")})
- @Version 設置樂觀鎖定
- @Cache 設置二級緩存
- @Filters 設置使用過濾器
- @FilterDef 聲明過濾器
demo
比如有2個表 一個CATEGORY
- -- Create table
- create table CATEGORY
- (
- ID NUMBER(8) not null,
- NAME NVARCHAR2(200),
- DESCRIPTION VARCHAR2(1000)
- )
- tablespace USERS
- pctfree 10
- initrans 1
- maxtrans 255
- storage
- (
- initial 64K
- minextents 1
- maxextents unlimited
- );
- -- Create/Recreate primary, unique and foreign key constraints
- alter table CATEGORY
- add constraint CATEGORY_PK primary key (ID)
- using index
- tablespace USERS
- pctfree 10
- initrans 2
- maxtrans 255
- storage
- (
- initial 64K
- minextents 1
- maxextents unlimited
- );
一個PRODUCT
- -- Create table
- create table PRODUCT
- (
- ID NUMBER(8) not null,
- NAME VARCHAR2(200),
- PRICE NUMBER(6,2),
- DESCRIPTION VARCHAR2(1000),
- CREATE_TIME DATE,
- CATEGORY_ID NUMBER(8)
- )
- tablespace USERS
- pctfree 10
- initrans 1
- maxtrans 255
- storage
- (
- initial 64K
- minextents 1
- maxextents unlimited
- );
- -- Create/Recreate primary, unique and foreign key constraints
- alter table PRODUCT
- add constraint PRODUCT_PK primary key (ID)
- using index
- tablespace USERS
- pctfree 10
- initrans 2
- maxtrans 255
- storage
- (
- initial 64K
- minextents 1
- maxextents unlimited
- );
- alter table PRODUCT
- add constraint PRODUCT_FK foreign key (CATEGORY_ID)
- references CATEGORY (ID);
可用MyEclipse 生成對應的持久化類,區別 平時的hibernate 創建的都是*.hbm.xml而現在是
add Hibernate mapping annotations to POJO
Category.Java
- import java.util.HashSet;
- import java.util.Set;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.OneToMany;
- import javax.persistence.Table;
- import org.hibernate.annotations.GenericGenerator;
- @Entity
- @Table(name = "CATEGORY", schema = "SCOTT")
- public class Category implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
- private Long id;
- private String name;
- private String description;
- private Set<Product> products = new HashSet<Product>(0);
- public Category() {
- }
- // Property accessors
- @GenericGenerator(name = "generator", strategy = "increment")
- @Id
- @GeneratedValue(generator = "generator")
- @Column(name = "ID", unique = true, nullable = false, precision = 8, scale = 0)
- public Long getId() {
- return this.id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- @Column(name = "NAME", length = 400)
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @Column(name = "DESCRIPTION", length = 1000)
- public String getDescription() {
- return this.description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
- public Set<Product> getProducts() {
- return this.products;
- }
- public void setProducts(Set<Product> products) {
- this.products = products;
- }
- }
product.java
- import java.util.Date;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.ManyToOne;
- import javax.persistence.Table;
- import javax.persistence.Temporal;
- import javax.persistence.TemporalType;
- import org.hibernate.annotations.GenericGenerator;
- @Entity
- @Table(name = "PRODUCT", schema = "SCOTT")
- public class Product implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
- private Long id;
- private Category category;
- private String name;
- private Double price;
- private String description;
- private Date createTime;
- public Product() {
- }
- @GenericGenerator(name = "generator", strategy = "increment")
- @Id
- @GeneratedValue(generator = "generator")
- @Column(name = "ID", unique = true, nullable = false, precision = 8, scale = 0)
- public Long getId() {
- return this.id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- @ManyToOne(fetch = FetchType.LAZY)
- @JoinColumn(name = "CATEGORY_ID")
- public Category getCategory() {
- return this.category;
- }
- public void setCategory(Category category) {
- this.category = category;
- }
- @Column(name = "NAME", length = 200)
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @Column(name = "PRICE", precision = 6)
- public Double getPrice() {
- return this.price;
- }
- public void setPrice(Double price) {
- this.price = price;
- }
- @Column(name = "DESCRIPTION", length = 1000)
- public String getDescription() {
- return this.description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- @Temporal(TemporalType.DATE)
- @Column(name = "CREATE_TIME", length = 7)
- public Date getCreateTime() {
- return this.createTime;
- }
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
- }
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.AnnotationConfiguration;
- public class HibernateAnnotationsTest {
- public void testAnnotations() {
- SessionFactory sessionFactory = new AnnotationConfiguration().configure()
- .buildSessionFactory();
- Session session = sessionFactory.getCurrentSession();
- Category category = new Category();
- category.setName("demo");
- category.setDescription("這是一個例子");
- Product product = new Product();
- product.setName("妮維雅");
- product.setPrice(new Double(46.0));
- product.setDescription("護膚品");
- product.setCategory(category);
- category.getProducts().add(product);
- Transaction tx = session.beginTransaction();
- session.save(category);
- session.save(product);
- tx.commit();
- sessionFactory.close();
- }
- public static void main(String[] args) {
- HibernateAnnotationsTest test = new HibernateAnnotationsTest();
- test.testAnnotations();
- }
- }
注意: 回報這種錯誤 java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor;
解決方法 替換hibernate-annotation.jar 和hibernate-validator.jar 換成新點的 或者你把hibernate-validator.jar 移除也行
hibernate-annotation.jar 換成3.4.0的就好了,3.5.1-Final還會報一個缺少MetadataProvider的類具體沒太注意解決的方法,validator我換的是4.0.2的其他的沒測試應該也沒什么問題...
@GeneratedValue注解生成策略
TABLE 借助數據庫表,生成存標識符屬性值,表中保存當前的標識符屬性的最大值
IDENTITY 使用數據庫表中的自動增長字段生成標識符屬性值
SEQUENCE 使用數據庫的序列生成標識符屬性值
AUTO 可以是上面三種任意一種類型,取決於底層數據庫的類型
Hibernate EntityManager
Java Persistence API(JPA)
java persistence api 是ejb3.0規范之一,定義了對數據庫數據進行持久化操作的接口,Hibernate使用 Hibernate annotations和Hibernate EntityManager實現了JPA
會使用到 Hibernate-EntityManager.jar和jboss-archive-browing.jar
和Annotation不同的是沒有用到hibernate.cfg.xml 而是使用persistence.xml文件的實現填寫信息而xml文件必須在META-INF文件夾下其余的基本相同
persistence.xml
- <?xml version='1.0' encoding='UTF-8'?>
- <persistence xmlns="http://java.sun.com/xml/ns/persistence"
- xmlns:xsi="http://www.23.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/ns/persistence http://java.sun.com/ns/persistence/persistence_1_0.xsd"
- version="1.0">
- <persistence-unit name="entityManagerTest">
- <provider>org.hibernate.ejb.HibernatePersistence
- </provider>
- <properties>
- <property name="hibernate.archive.autodetection" value="class, hbm" />
- <property name="hibernate.show_sql" value="true" />
- <property name="hibernate.format_sql" value="true" />
- <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
- <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
- <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:dbrbh" />
- <property name="hibernate.connection.username" value="scott" />
- <property name="hibernate.connection.password" value="tiger" />
- </properties>
- </persistence-unit>
- </persistence>
- //EntityManagerFactory==SessionFactory
- EntityManagerFactory emf = Persistence.createEntityManagerFactory("entityManagerTest");
- //EntityManager == session
- EntityManager entityManager = emf.createEntityManager();
- //EntityTransaction == Transaction
- EntityTransaction tx = entityManager.getTransaction();
- //entityManager persist()=Session.save()
- entityManager.persist(category);
- import org.hibernate.annotations.Cache;
- import org.hibernate.annotations.CacheConcurrencyStrategy;
- import org.hibernate.annotations.GenericGenerator;
- @Entity
- @Table(name="profile")
- @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
- public class Profile implements Serializable{}
hibernate.cfg.xml
- <hibernate-configuration>
- <session-factory>
- <mapping class="com.ztesec.orm.model.Admin" />
- <mapping class="com.ztesec.orm.model.Role" />
- <mapping class="com.ztesec.orm.model.Profile" />
- <mapping class="com.ztesec.orm.model.Profile_info" />
- <mapping class="com.ztesec.orm.model.Log" />
- <class-cache class="com.ztesec.orm.model.Admin" usage="read-only" />
- <class-cache class="com.ztesec.orm.model.Role" usage="read-only" />
- <class-cache class="com.ztesec.orm.model.Profile" usage="read-only" />
- <class-cache class="com.ztesec.orm.model.Profile_info" usage="read-only" />
- <class-cache class="com.ztesec.orm.model.Log" usage="read-only" />
- </session-factory>
- </hibernate-configuration>
- <diskStore path="D:/src/cachetmpdir"/>
- <defaultCache
- maxElementsInMemory="500"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="true"
- />
- <cache name="com.ztesec.orm.model.Admin"
- maxElementsInMemory="500"
- eternal="false"
- timeToIdleSeconds="50"
- timeToLiveSeconds="50"
- overflowToDisk="true"
- />
- <cache name="com.ztesec.orm.model.Profile"
- maxElementsInMemory="500"
- eternal="false"
- timeToIdleSeconds="50"
- timeToLiveSeconds="50"
- overflowToDisk="true"
- />
- <cache name="com.ztesec.orm.model.Profile_info"
- maxElementsInMemory="500"
- eternal="false"
- timeToIdleSeconds="50"
- timeToLiveSeconds="50"
- overflowToDisk="true"
- />
- <cache name="caseCache" maxElementsInMemory="10"
- maxElementsOnDisk="10" eternal="false" overflowToDisk="false"
- diskSpoolBufferSizeMB="200" timeToIdleSeconds="1800" timeToLiveSeconds="1800"
- memoryStoreEvictionPolicy="LFU" />
- <cache name="msgCache" maxElementsInMemory="10000"
- maxElementsOnDisk="1000" eternal="false" overflowToDisk="false"
- diskSpoolBufferSizeMB="500" timeToIdleSeconds="300" timeToLiveSeconds="300"
- memoryStoreEvictionPolicy="LFU" />
- </ehcache>
ehcache.xml
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
- <diskStore path="java.io.tmpdir"/>
- <!--
- Mandatory Default Cache configuration. These settings will be applied to caches
- created programmtically using CacheManager.add(String cacheName)
- -->
- <!--
- name:緩存名稱。
- maxElementsInMemory:緩存最大個數。
- eternal:對象是否永久有效,一但設置了,timeout將不起作用。
- timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。
- timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
- overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
- diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。
- maxElementsOnDisk:硬盤最大緩存個數。
- diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
- diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
- memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。
- clearOnFlush:內存數量最大時是否清除。
- -->
- <defaultCache
- maxElementsInMemory="10000"
- eternal="false"
- timeToIdleSeconds="120"
- timeToLiveSeconds="120"
- overflowToDisk="true"
- maxElementsOnDisk="10000000"
- diskPersistent="false"
- diskExpiryThreadIntervalSeconds="120"
- memoryStoreEvictionPolicy="LRU"
- />
- </ehcache>