Hibernate Annotations 注解

时间:2023-03-10 07:09:13
Hibernate Annotations 注解

Hibernate Annotations 注解

 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么使用,但是hibernate中也封装了javax.persistence,而且数据库映射注释主要还是使用javax.persistence,即如下注释元素Column,使用规则如下。

Hibernate Annotations 注解 分类:
Java(66) Hibernate Annotations 注解
  1. @Entity 声明当前是一个持久化类
  2. @Table 设置当前持久化类所映射的数据库表,如果当前类中没有使用@Table注解,Hibernate会自动使用默认的持久化类的类名(不带包名)作为所映射的表名
  3. @Id  设置当前持久化类的标示符属性
  4. @GeneratedValue 设置当前标示符的生产策略。@GeneratedValue的name属性设置生成策略的名称是TABLE、INENTITY、SEQUENCE或者AUTO之一。
  5. @Column  将持久化类的数学与数据库表中的字段进行映射,name属性值为映射的字段名,length属性值为字段的长度,unique属性表示该列上设置唯一的约束,nullable属性设置该列的值是否可以为空,precision实现设置该字段的精度,scale属性设置该字段的小数位数
  6. @Transient 标注的属性进行持久化映射
  7. @Temporal java中没有定义时间精度的api,因此处理时间类型数据时,需要设置存储在数据库中所预期的精度,使用@Temporal注释可以调整时间的精度为:DATE、TIME和TIMESTAMP三种
  8. @ManyToOne  设置该当前持久化类类与其他持久化类之间的多对一关联,其中CascadeType值表示Hibernate将进行级联操作
  9. @OneToMany  设置该当前持久化类与其他持久化类之间的一对多关联
  10. @OneToOne   设置该当前持久化类与其他持久化类之间的一对一关联
  11. @ManyToMany 设置该当前持久化类与其他持久化类之间的多对多关联
  12. @NameQueries 在持久化类中设置命名查询,参考@NameQuery的使用
  13. @NameQuery   在持久化类中设置命名查询,@NamedQuery 和@NamedQueries注释加在在类和包上。如下面的例子:
  14. @NamedQueries({@NamedQuery(name="queryById",query="select p from Product p where id=:id")})
  15. @Version 设置乐观锁定
  16. @Cache 设置二级缓存
  17. @Filters  设置使用过滤器
  18. @FilterDef  声明过滤器

demo

比如有2个表 一个CATEGORY

  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

  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

  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. @Entity
  13. @Table(name = "CATEGORY", schema = "SCOTT")
  14. public class Category implements java.io.Serializable {
  15. private static final long serialVersionUID = 1L;
  16. private Long id;
  17. private String name;
  18. private String description;
  19. private Set<Product> products = new HashSet<Product>(0);
  20. public Category() {
  21. }
  22. // Property accessors
  23. @GenericGenerator(name = "generator", strategy = "increment")
  24. @Id
  25. @GeneratedValue(generator = "generator")
  26. @Column(name = "ID", unique = true, nullable = false, precision = 8, scale = 0)
  27. public Long getId() {
  28. return this.id;
  29. }
  30. public void setId(Long id) {
  31. this.id = id;
  32. }
  33. @Column(name = "NAME", length = 400)
  34. public String getName() {
  35. return this.name;
  36. }
  37. public void setName(String name) {
  38. this.name = name;
  39. }
  40. @Column(name = "DESCRIPTION", length = 1000)
  41. public String getDescription() {
  42. return this.description;
  43. }
  44. public void setDescription(String description) {
  45. this.description = description;
  46. }
  47. @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
  48. public Set<Product> getProducts() {
  49. return this.products;
  50. }
  51. public void setProducts(Set<Product> products) {
  52. this.products = products;
  53. }
  54. }

product.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. @Entity
  14. @Table(name = "PRODUCT", schema = "SCOTT")
  15. public class Product implements java.io.Serializable {
  16. private static final long serialVersionUID = 1L;
  17. private Long id;
  18. private Category category;
  19. private String name;
  20. private Double price;
  21. private String description;
  22. private Date createTime;
  23. public Product() {
  24. }
  25. @GenericGenerator(name = "generator", strategy = "increment")
  26. @Id
  27. @GeneratedValue(generator = "generator")
  28. @Column(name = "ID", unique = true, nullable = false, precision = 8, scale = 0)
  29. public Long getId() {
  30. return this.id;
  31. }
  32. public void setId(Long id) {
  33. this.id = id;
  34. }
  35. @ManyToOne(fetch = FetchType.LAZY)
  36. @JoinColumn(name = "CATEGORY_ID")
  37. public Category getCategory() {
  38. return this.category;
  39. }
  40. public void setCategory(Category category) {
  41. this.category = category;
  42. }
  43. @Column(name = "NAME", length = 200)
  44. public String getName() {
  45. return this.name;
  46. }
  47. public void setName(String name) {
  48. this.name = name;
  49. }
  50. @Column(name = "PRICE", precision = 6)
  51. public Double getPrice() {
  52. return this.price;
  53. }
  54. public void setPrice(Double price) {
  55. this.price = price;
  56. }
  57. @Column(name = "DESCRIPTION", length = 1000)
  58. public String getDescription() {
  59. return this.description;
  60. }
  61. public void setDescription(String description) {
  62. this.description = description;
  63. }
  64. @Temporal(TemporalType.DATE)
  65. @Column(name = "CREATE_TIME", length = 7)
  66. public Date getCreateTime() {
  67. return this.createTime;
  68. }
  69. public void setCreateTime(Date createTime) {
  70. this.createTime = createTime;
  71. }
  72. }
  1. import org.hibernate.Session;
  2. import org.hibernate.SessionFactory;
  3. import org.hibernate.Transaction;
  4. import org.hibernate.cfg.AnnotationConfiguration;
  5. public class HibernateAnnotationsTest {
  6. public void testAnnotations() {
  7. SessionFactory sessionFactory = new AnnotationConfiguration().configure()
  8. .buildSessionFactory();
  9. Session session = sessionFactory.getCurrentSession();
  10. Category category = new Category();
  11. category.setName("demo");
  12. category.setDescription("这是一个例子");
  13. Product product = new Product();
  14. product.setName("妮维雅");
  15. product.setPrice(new Double(46.0));
  16. product.setDescription("护肤品");
  17. product.setCategory(category);
  18. category.getProducts().add(product);
  19. Transaction tx = session.beginTransaction();
  20. session.save(category);
  21. session.save(product);
  22. tx.commit();
  23. sessionFactory.close();
  24. }
  25. public static void main(String[] args) {
  26. HibernateAnnotationsTest test = new HibernateAnnotationsTest();
  27. test.testAnnotations();
  28. }
  29. }

注意: 回报这种错误 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

JavaPersistence 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

  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>
  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);
  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

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

ehcache.xml

  1. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
  2. <diskStore path="java.io.tmpdir"/>
  3. <!--
  4. Mandatory Default Cache configuration. These settings will be applied to caches
  5. created programmtically using CacheManager.add(String cacheName)
  6. -->
  7. <!--
  8. name:缓存名称。
  9. maxElementsInMemory:缓存最大个数。
  10. eternal:对象是否永久有效,一但设置了,timeout将不起作用。
  11. timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
  12. timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
  13. overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
  14. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
  15. maxElementsOnDisk:硬盘最大缓存个数。
  16. diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
  17. diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
  18. memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
  19. clearOnFlush:内存数量最大时是否清除。
  20. -->
  21. <defaultCache
  22. maxElementsInMemory="10000"
  23. eternal="false"
  24. timeToIdleSeconds="120"
  25. timeToLiveSeconds="120"
  26. overflowToDisk="true"
  27. maxElementsOnDisk="10000000"
  28. diskPersistent="false"
  29. diskExpiryThreadIntervalSeconds="120"
  30. memoryStoreEvictionPolicy="LRU"
  31. />
  32. </ehcache>