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>  
原文地址:https://www.cnblogs.com/w-wfy/p/6265650.html