对于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 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
- );
- 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 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
- );
- 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() {
- }
-
-
- @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 emf = Persistence.createEntityManagerFactory("entityManagerTest");
-
- EntityManager entityManager = emf.createEntityManager();
-
- EntityTransaction tx = entityManager.getTransaction();
- 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>