Hibernate Annotations 注解
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
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
- <?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>
Hibernate Annotations 注解的更多相关文章
- 2.2、Hibernate用注解方式实现一对多、多对多关系
一.一对多关系 1.在上一篇日志中用.xml配置文件项目基础上,再往lib目录先添加一个包-hibernate-jpa-2.0-api-1.0.0.Final.jar 2.新建一个com.st.bea ...
- Hibernate用注解实现实体类和表的映射
数据库mysql: 1.一对一 person50表password50表是一对一的关系: password50表中有外键 person_id person实体类: package com.c50.en ...
- Hibernate @Formula 注解方式
1.Formula的作用 Formula的作用就是用一个查询语句动态的生成一个类的属性 就是一条select count(*)...构成的虚拟列,而不是存储在数据库里的一个字段.用比较标准的说法就是: ...
- hibernate基于注解的维护权反转:@OneToMany(mappedBy=)
背景说明:首先是SSH环境下,对象基于注解的方式映射到数据库: 昨天遇到一个比较纠结的问题,@OneToMany(mappedBy="xxx"), mappedBy属性有什么用,然 ...
- Hibernate基于注解方式配置来实现实体和数据库之间存在某种映射关系
实体和数据库之间存在某种映射关系,hibernate根据这种映射关系完成数据的存取.在程序中这种映射关系由映射文件(*.hbm.xml)或者java注解(@)定义. 本文以java注解的形式总结映射关 ...
- Hibernate - 使用注解完成映射
除了使用XML配置来映射对象和数据库表,还可以使用注解来完成持久化.使用注解需要导入Hibernate Annotations扩展包 @Entity -加在类的前面,将类声明为持久化类. -javax ...
- BAE 环境下 hibernate annotations 配置
annotations 配置 首先需要加入 hibernate-jpa-2.0-api-1.0.1.Final.jar 和 ejb3-persistence.jar 这两个包 ejb3-persis ...
- hibernate使用注解简化开发
简述 在编写hibernate的时候,需要将实体类映射到数据库中的表.通常需要一个配置文件(hibernate.cfg.xml),一个实体类(XX.Java),还有一个映射文件(XX.hbm.xml) ...
- Hibernate用注解生成表
User.java实体来 package com.tao.pojo; import javax.persistence.Column; //用注解的方式生成表 import javax.persist ...
随机推荐
- 如何下载flash离线安装包
如何下载flash离线安装包 CreateTime--2018年4月14日16:02:13 Author:Marydon 1.下载地址 UpdateTime--2018年5月13日16点55分 p ...
- ubuntu建立软ap共享无线网络
建立ad-hoc模式共享网络 viewtopic.php?f=116&t=387194 有些android手机可能不支持ad-hoc模式,要第三方rom才行. 首先安装这些工具 代码: apt ...
- Android4.0源码Launcher启动流程分析【android源码Launcher系列一】
最近研究ICS4.0的Launcher,发现4.0和2.3有稍微点区别,但是区别不是特别大,所以我就先整理一下Launcher启动的大致流程. Launcher其实是贯彻于手机的整个系统的,时时刻刻都 ...
- Redis全方位讲解--主从复制(转载)
前言 前面介绍了redis持久化和容灾备份,这篇会介绍redis主从复制和redis持久化在主从复制中的一些应用.因为本人没有那么多服务器或机器,所以这里主要介绍下如何在docker容器中搭建主从复制 ...
- EMQ ---客户端clientid为空,emq会随机帮忙生成
mqtt v3.1.1协议有规定clientid可以为空,所以当客户端clientid为空,emq会随机帮忙生成. 如果clientid为空,随机生成clientid.例如'emqttd_105789 ...
- Refresh Tokens: When to Use Them and How They Interact with JWTs
In this post we will explore the concept of refresh tokens as defined by OAuth2. We will learn why t ...
- Jquery.Treeview+Jquery UI制作Web文件预览
效果图: 前台Html: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="D ...
- Atitit.软件仪表盘(2)--vm子系统--资源占用监测
Atitit.软件仪表盘(2)--vm子系统--资源占用监测 1. Jvisualvm.exe 2. jprofile 3. Heap //permgen monitor 作者::老哇的爪子At ...
- X86平台简称
1.PCH:PCH全称为Platform Controller Hub,是intel公司的集成南桥.AMD SB700/710/750 http://support.amd.com/TechDocs ...
- iOS图片压缩上传
本文实例为大家分享了iOS实现压缩图片上传功能,供大家参考,具体内容如下 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2 ...