Hibernate Annotations 注解


Hibernate Annotations 注解

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

 分類:
[java]  view plain  copy
 
  1. @Entity 聲明當前是一個持久化類    
  2.     
  3. @Table 設置當前持久化類所映射的數據庫表,如果當前類中沒有使用@Table注解,Hibernate會自動使用默認的持久化類的類名(不帶包名)作為所映射的表名    
  4.     
  5. @Id  設置當前持久化類的標示符屬性    
  6.     
  7. @GeneratedValue 設置當前標示符的生產策略。@GeneratedValue的name屬性設置生成策略的名稱是TABLE、INENTITY、SEQUENCE或者AUTO之一。    
  8.     
  9. @Column  將持久化類的數學與數據庫表中的字段進行映射,name屬性值為映射的字段名,length屬性值為字段的長度,unique屬性表示該列上設置唯一的約束,nullable屬性設置該列的值是否可以為空,precision實現設置該字段的精度,scale屬性設置該字段的小數位數    
  10.     
  11. @Transient 標注的屬性進行持久化映射    
  12.     
  13. @Temporal java中沒有定義時間精度的api,因此處理時間類型數據時,需要設置存儲在數據庫中所預期的精度,使用@Temporal注釋可以調整時間的精度為:DATE、TIME和TIMESTAMP三種    
  14.     
  15. @ManyToOne  設置該當前持久化類類與其他持久化類之間的多對一關聯,其中CascadeType值表示Hibernate將進行級聯操作    
  16.     
  17. @OneToMany  設置該當前持久化類與其他持久化類之間的一對多關聯    
  18.     
  19. @OneToOne   設置該當前持久化類與其他持久化類之間的一對一關聯    
  20.     
  21. @ManyToMany 設置該當前持久化類與其他持久化類之間的多對多關聯    
  22.     
  23. @NameQueries 在持久化類中設置命名查詢,參考@NameQuery的使用    
  24.     
  25. @NameQuery   在持久化類中設置命名查詢,@NamedQuery 和@NamedQueries注釋加在在類和包上。如下面的例子:    
  26. @NamedQueries({@NamedQuery(name="queryById",query="select p from Product p where id=:id")})    
  27.     
  28. @Version 設置樂觀鎖定    
  29.     
  30. @Cache 設置二級緩存    
  31.     
  32. @Filters  設置使用過濾器    
  33.     
  34. @FilterDef  聲明過濾器    

demo

比如有2個表 一個CATEGORY

Sql代碼   收藏代碼
  1. -- Create table  
  2. create table CATEGORY  
  3. (  
  4.   ID          NUMBER(8) not null,  
  5.   NAME        NVARCHAR2(200),  
  6.   DESCRIPTION VARCHAR2(1000)  
  7. )  
  8. tablespace USERS  
  9.   pctfree 10  
  10.   initrans 1  
  11.   maxtrans 255  
  12.   storage  
  13.   (  
  14.     initial 64K  
  15.     minextents 1  
  16.     maxextents unlimited  
  17.   );  
  18. -- Create/Recreate primary, unique and foreign key constraints   
  19. alter table CATEGORY  
  20.   add constraint CATEGORY_PK primary key (ID)  
  21.   using index   
  22.   tablespace USERS  
  23.   pctfree 10  
  24.   initrans 2  
  25.   maxtrans 255  
  26.   storage  
  27.   (  
  28.     initial 64K  
  29.     minextents 1  
  30.     maxextents unlimited  
  31.   );  

 

   一個PRODUCT

Sql代碼   收藏代碼
  1. -- Create table  
  2. create table PRODUCT  
  3. (  
  4.   ID          NUMBER(8) not null,  
  5.   NAME        VARCHAR2(200),  
  6.   PRICE       NUMBER(6,2),  
  7.   DESCRIPTION VARCHAR2(1000),  
  8.   CREATE_TIME DATE,  
  9.   CATEGORY_ID NUMBER(8)  
  10. )  
  11. tablespace USERS  
  12.   pctfree 10  
  13.   initrans 1  
  14.   maxtrans 255  
  15.   storage  
  16.   (  
  17.     initial 64K  
  18.     minextents 1  
  19.     maxextents unlimited  
  20.   );  
  21. -- Create/Recreate primary, unique and foreign key constraints   
  22. alter table PRODUCT  
  23.   add constraint PRODUCT_PK primary key (ID)  
  24.   using index   
  25.   tablespace USERS  
  26.   pctfree 10  
  27.   initrans 2  
  28.   maxtrans 255  
  29.   storage  
  30.   (  
  31.     initial 64K  
  32.     minextents 1  
  33.     maxextents unlimited  
  34.   );  
  35. alter table PRODUCT  
  36.   add constraint PRODUCT_FK foreign key (CATEGORY_ID)  
  37.   references CATEGORY (ID);  

 

 可用MyEclipse 生成對應的持久化類,區別 平時的hibernate 創建的都是*.hbm.xml而現在是

add  Hibernate mapping annotations to POJO

Category.Java

Java代碼   收藏代碼
  1. import java.util.HashSet;  
  2. import java.util.Set;  
  3. import javax.persistence.CascadeType;  
  4. import javax.persistence.Column;  
  5. import javax.persistence.Entity;  
  6. import javax.persistence.FetchType;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.Id;  
  9. import javax.persistence.OneToMany;  
  10. import javax.persistence.Table;  
  11. import org.hibernate.annotations.GenericGenerator;  
  12.   
  13. @Entity  
  14. @Table(name = "CATEGORY", schema = "SCOTT")  
  15. public class Category implements java.io.Serializable {  
  16.   
  17.     private static final long serialVersionUID = 1L;  
  18.     private Long id;  
  19.     private String name;  
  20.     private String description;  
  21.     private Set<Product> products = new HashSet<Product>(0);  
  22.   
  23.     public Category() {  
  24.     }  
  25.   
  26.     // Property accessors  
  27.     @GenericGenerator(name = "generator", strategy = "increment")  
  28.     @Id  
  29.     @GeneratedValue(generator = "generator")  
  30.     @Column(name = "ID", unique = true, nullable = false, precision = 8, scale = 0)  
  31.     public Long getId() {  
  32.         return this.id;  
  33.     }  
  34.   
  35.     public void setId(Long id) {  
  36.         this.id = id;  
  37.     }  
  38.   
  39.     @Column(name = "NAME", length = 400)  
  40.     public String getName() {  
  41.         return this.name;  
  42.     }  
  43.   
  44.     public void setName(String name) {  
  45.         this.name = name;  
  46.     }  
  47.   
  48.     @Column(name = "DESCRIPTION", length = 1000)  
  49.     public String getDescription() {  
  50.         return this.description;  
  51.     }  
  52.   
  53.     public void setDescription(String description) {  
  54.         this.description = description;  
  55.     }  
  56.   
  57.     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")  
  58.     public Set<Product> getProducts() {  
  59.         return this.products;  
  60.     }  
  61.   
  62.     public void setProducts(Set<Product> products) {  
  63.         this.products = products;  
  64.     }  
  65.   
  66. }  

 

product.java

Java代碼   收藏代碼
  1. import java.util.Date;  
  2. import javax.persistence.Column;  
  3. import javax.persistence.Entity;  
  4. import javax.persistence.FetchType;  
  5. import javax.persistence.GeneratedValue;  
  6. import javax.persistence.Id;  
  7. import javax.persistence.JoinColumn;  
  8. import javax.persistence.ManyToOne;  
  9. import javax.persistence.Table;  
  10. import javax.persistence.Temporal;  
  11. import javax.persistence.TemporalType;  
  12. import org.hibernate.annotations.GenericGenerator;  
  13.   
  14. @Entity  
  15. @Table(name = "PRODUCT", schema = "SCOTT")  
  16. public class Product implements java.io.Serializable {  
  17.     private static final long serialVersionUID = 1L;  
  18.     private Long id;  
  19.     private Category category;  
  20.     private String name;  
  21.     private Double price;  
  22.     private String description;  
  23.     private Date createTime;  
  24.   
  25.     public Product() {  
  26.     }  
  27.   
  28.     @GenericGenerator(name = "generator", strategy = "increment")  
  29.     @Id  
  30.     @GeneratedValue(generator = "generator")  
  31.     @Column(name = "ID", unique = true, nullable = false, precision = 8, scale = 0)  
  32.     public Long getId() {  
  33.         return this.id;  
  34.     }  
  35.   
  36.     public void setId(Long id) {  
  37.         this.id = id;  
  38.     }  
  39.   
  40.     @ManyToOne(fetch = FetchType.LAZY)  
  41.     @JoinColumn(name = "CATEGORY_ID")  
  42.     public Category getCategory() {  
  43.         return this.category;  
  44.     }  
  45.   
  46.     public void setCategory(Category category) {  
  47.         this.category = category;  
  48.     }  
  49.   
  50.     @Column(name = "NAME", length = 200)  
  51.     public String getName() {  
  52.         return this.name;  
  53.     }  
  54.   
  55.     public void setName(String name) {  
  56.         this.name = name;  
  57.     }  
  58.   
  59.     @Column(name = "PRICE", precision = 6)  
  60.     public Double getPrice() {  
  61.         return this.price;  
  62.     }  
  63.   
  64.     public void setPrice(Double price) {  
  65.         this.price = price;  
  66.     }  
  67.   
  68.     @Column(name = "DESCRIPTION", length = 1000)  
  69.     public String getDescription() {  
  70.         return this.description;  
  71.     }  
  72.   
  73.     public void setDescription(String description) {  
  74.         this.description = description;  
  75.     }  
  76.   
  77.     @Temporal(TemporalType.DATE)  
  78.     @Column(name = "CREATE_TIME", length = 7)  
  79.     public Date getCreateTime() {  
  80.         return this.createTime;  
  81.     }  
  82.   
  83.     public void setCreateTime(Date createTime) {  
  84.         this.createTime = createTime;  
  85.     }  
  86.   
  87. }  

 

Java代碼   收藏代碼
  1. import org.hibernate.Session;  
  2. import org.hibernate.SessionFactory;  
  3. import org.hibernate.Transaction;  
  4. import org.hibernate.cfg.AnnotationConfiguration;  
  5.   
  6. public class HibernateAnnotationsTest {  
  7.     public void testAnnotations() {  
  8.         SessionFactory sessionFactory = new AnnotationConfiguration().configure()  
  9.                 .buildSessionFactory();  
  10.         Session session = sessionFactory.getCurrentSession();  
  11.   
  12.         Category category = new Category();  
  13.         category.setName("demo");  
  14.         category.setDescription("這是一個例子");  
  15.   
  16.         Product product = new Product();  
  17.         product.setName("妮維雅");  
  18.         product.setPrice(new Double(46.0));  
  19.         product.setDescription("護膚品");  
  20.   
  21.         product.setCategory(category);  
  22.         category.getProducts().add(product);  
  23.   
  24.         Transaction tx = session.beginTransaction();  
  25.         session.save(category);  
  26.         session.save(product);  
  27.         tx.commit();  
  28.         sessionFactory.close();  
  29.     }  
  30.   
  31.     public static void main(String[] args) {  
  32.         HibernateAnnotationsTest test = new HibernateAnnotationsTest();  
  33.         test.testAnnotations();  
  34.     }  
  35. }  

 

注意: 回報這種錯誤 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代碼   收藏代碼
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <persistence xmlns="http://java.sun.com/xml/ns/persistence"  
  3.     xmlns:xsi="http://www.23.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/ns/persistence http://java.sun.com/ns/persistence/persistence_1_0.xsd"  
  5.     version="1.0">  
  6.     <persistence-unit name="entityManagerTest">  
  7.         <provider>org.hibernate.ejb.HibernatePersistence  
  8.         </provider>  
  9.         <properties>  
  10.             <property name="hibernate.archive.autodetection" value="class, hbm" />  
  11.             <property name="hibernate.show_sql" value="true" />  
  12.             <property name="hibernate.format_sql" value="true" />  
  13.             <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />  
  14.             <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />  
  15.             <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:dbrbh" />  
  16.             <property name="hibernate.connection.username" value="scott" />  
  17.             <property name="hibernate.connection.password" value="tiger" />             
  18.         </properties>  
  19.     </persistence-unit>  
  20. </persistence>  

 

 

Java代碼   收藏代碼
  1. //EntityManagerFactory==SessionFactory  
  2.     EntityManagerFactory emf = Persistence.createEntityManagerFactory("entityManagerTest");  
  3.     //EntityManager == session  
  4.     EntityManager entityManager = emf.createEntityManager();  
  5.     //EntityTransaction == Transaction  
  6.     EntityTransaction tx = entityManager.getTransaction();  
  7. //entityManager persist()=Session.save()  
  8.     entityManager.persist(category);  
[java]  view plain  copy
 
  1. import org.hibernate.annotations.Cache;  
  2. import org.hibernate.annotations.CacheConcurrencyStrategy;  
  3. import org.hibernate.annotations.GenericGenerator;  
  4. @Entity  
  5. @Table(name="profile")  
  6. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  
  7. public class Profile implements Serializable{}  

 

hibernate.cfg.xml

[java]  view plain  copy
 
  1. <hibernate-configuration>  
  2.     <session-factory>  
  3.         <mapping class="com.ztesec.orm.model.Admin" />  
  4.         <mapping class="com.ztesec.orm.model.Role" />  
  5.         <mapping class="com.ztesec.orm.model.Profile" />  
  6.         <mapping class="com.ztesec.orm.model.Profile_info" />  
  7.           
  8.         <mapping class="com.ztesec.orm.model.Log" />  
  9.           
  10.           
  11.         <class-cache class="com.ztesec.orm.model.Admin" usage="read-only" />  
  12.         <class-cache class="com.ztesec.orm.model.Role" usage="read-only" />  
  13.         <class-cache class="com.ztesec.orm.model.Profile" usage="read-only" />  
  14.         <class-cache class="com.ztesec.orm.model.Profile_info" usage="read-only" />  
  15.         <class-cache class="com.ztesec.orm.model.Log" usage="read-only" />  
  16.     </session-factory>  
  17. </hibernate-configuration>  
[java]  view plain  copy
 
  1. <diskStore path="D:/src/cachetmpdir"/>  
  2.         
  3.     <defaultCache  
  4.                 maxElementsInMemory="500"  
  5.                 eternal="false"  
  6.                 timeToIdleSeconds="120"  
  7.                 timeToLiveSeconds="120"  
  8.                 overflowToDisk="true"  
  9.                 />  
  10.              
  11.           <cache name="com.ztesec.orm.model.Admin"  
  12.                 maxElementsInMemory="500"  
  13.                 eternal="false"  
  14.                 timeToIdleSeconds="50"  
  15.                 timeToLiveSeconds="50"  
  16.                 overflowToDisk="true"  
  17.                 />  
  18.                 <cache name="com.ztesec.orm.model.Profile"  
  19.                 maxElementsInMemory="500"  
  20.                 eternal="false"  
  21.                 timeToIdleSeconds="50"  
  22.                 timeToLiveSeconds="50"  
  23.                 overflowToDisk="true"  
  24.                 />  
  25.                 <cache name="com.ztesec.orm.model.Profile_info"  
  26.                 maxElementsInMemory="500"  
  27.                 eternal="false"  
  28.                 timeToIdleSeconds="50"  
  29.                 timeToLiveSeconds="50"  
  30.                 overflowToDisk="true"  
  31.                 />  
  32.     <cache name="caseCache" maxElementsInMemory="10"    
  33.         maxElementsOnDisk="10" eternal="false" overflowToDisk="false"    
  34.         diskSpoolBufferSizeMB="200" timeToIdleSeconds="1800" timeToLiveSeconds="1800"    
  35.         memoryStoreEvictionPolicy="LFU" />   
  36.           
  37.     <cache name="msgCache" maxElementsInMemory="10000"    
  38.         maxElementsOnDisk="1000" eternal="false" overflowToDisk="false"    
  39.         diskSpoolBufferSizeMB="500" timeToIdleSeconds="300" timeToLiveSeconds="300"    
  40.         memoryStoreEvictionPolicy="LFU" />   
  41.           
  42. </ehcache>      


ehcache.xml

 

  1. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">  
  2.   
  3.     <diskStore path="java.io.tmpdir"/>  
  4.   
  5.     <!--  
  6.     Mandatory Default Cache configuration. These settings will be applied to caches  
  7.     created programmtically using CacheManager.add(String cacheName)  
  8.     -->  
  9.     <!--  
  10.        name:緩存名稱。  
  11.        maxElementsInMemory:緩存最大個數。  
  12.        eternal:對象是否永久有效,一但設置了,timeout將不起作用。  
  13.        timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。  
  14.        timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。  
  15.        overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。  
  16.        diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。  
  17.        maxElementsOnDisk:硬盤最大緩存個數。  
  18.        diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.  
  19.        diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。  
  20.        memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。  
  21.        clearOnFlush:內存數量最大時是否清除。  
  22.     -->  
  23.     <defaultCache  
  24.             maxElementsInMemory="10000"  
  25.             eternal="false"  
  26.             timeToIdleSeconds="120"  
  27.             timeToLiveSeconds="120"  
  28.             overflowToDisk="true"  
  29.             maxElementsOnDisk="10000000"  
  30.             diskPersistent="false"  
  31.             diskExpiryThreadIntervalSeconds="120"  
  32.             memoryStoreEvictionPolicy="LRU"  
  33.             />  
  34. </ehcache>  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM