通过@Entity注解将一个类声明为一个实体bean(即一个持久化POJO类), @Id注解则声明了该实体bean的标识属性. 其他的映射定义是隐式的.

就是说一个持久化POJO类,除了主键ID需要@Id显示注解,其他列都可以不做任何注解。

用例代码如下:

  • 数据库DDL语句:
 create table CAT
(
id VARCHAR2(32 CHAR) not null,
create_time TIMESTAMP(6),
update_time TIMESTAMP(6),
cat_name VARCHAR2(255 CHAR)
)
  • hibernate.cfg.xml
 <?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库驱动配置 -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="connection.username">wxuatuser</property>
<property name="connection.password">xlh</property>
<property name="show_sql">true</property>
<!-- 自动执行DDL属性是update,不是true -->
<property name="hbm2ddl.auto">update</property>
<!-- hibernate实体类 --> <mapping class="a1_Entity.Cat"/> </session-factory>
</hibernate-configuration>
  • java类
实体类 - 基类
 package model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator; /**
* 实体类 - 基类
*/
@MappedSuperclass
public class BaseEntity implements Serializable { private static final long serialVersionUID = -6718838800112233445L; private String id;// ID
private Date create_time;// 创建日期
private Date update_time;// 修改日期
@Id
@Column(length = 32, nullable = true)
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(updatable = false)
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
public Date getUpdate_time() {
return update_time;
}
public void setUpdate_time(Date update_time) {
this.update_time = update_time;
}
@Override
public int hashCode() {
return id == null ? System.identityHashCode(this) : id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass().getPackage() != obj.getClass().getPackage()) {
return false;
}
final BaseEntity other = (BaseEntity) obj;
if (id == null) {
if (other.getId() != null) {
return false;
}
} else if (!id.equals(other.getId())) {
return false;
}
return true;
}
}
实体类
 package a1_Entity;
import javax.persistence.Entity; import model.BaseEntity; @Entity
public class Cat extends BaseEntity{
/**
* 实体类
*/
private static final long serialVersionUID = -2776330321385582872L; private String cat_name; public String getCat_name() {
return cat_name;
} public void setCat_name(String cat_name) {
this.cat_name = cat_name;
}
}
Dao
 package daoUtil;

 import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static final SessionFactory sessionFactory; static {
try {
Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log exception!
throw new ExceptionInInitializerError(ex);
}
} public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
} public static Object save(Object obj){
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(obj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
return obj;
} public static void delete(Class<?> clazz,String id){
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Object obj = session.get(clazz,id);
session.delete(obj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
}
}
main
 package a1_Entity;

 import daoUtil.HibernateUtil;

 public class Test_Entity {

     public static void main(String[] args) {
Cat cat = new Cat();
cat.setId("1");
cat.setCat_name("test1@Entity");
HibernateUtil.save(cat);
}
}

环境:JDK1.6,MAVEN

源码地址:http://files.cnblogs.com/files/xiluhua/hibernate%40Entity.rar

Hibernate,JPA注解@Entity的更多相关文章

  1. Java、Hibernate(JPA)注解大全

    1.@Entity(name=”EntityName”) 必须,name为可选,对应数据库中一的个表 2.@Table(name=””,catalog=””,schema=””) 可选,通常和@Ent ...

  2. hibernate jpa 注解 @Temporal(TemporalType.DATE) 格式化时间日期,页面直接得到格式化类型的值

    1.日期: @Temporal(TemporalType.DATE) @Column(name = "applyDate", nullable = false, length = ...

  3. 【hibernate/JPA】注解方式实现 复合主键【spring boot】

    1>hibernate/JPA实现复合主键的思路:是将所有的主键属性封装在一个主键类中,提供给需要复合主键的实体类使用. 2>主键类的几点要求: . 使用复合主键的实体类必须实现Seria ...

  4. springBoot注解大全JPA注解springMVC相关注解全局异常处理

    https://www.cnblogs.com/tanwei81/p/6814022.html 一.注解(annotations)列表 @SpringBootApplication:包含了@Compo ...

  5. jpa遇到的 org.hibernate.PersistentObjectException: detached entity passed to persist异常

    jpa遇到的 org.hibernate.PersistentObjectException: detached entity passed to persist异常 发生这个原因是因为我们已经在实体 ...

  6. Hibernate,JPA注解@Embeddable

    JPA嵌入式对象(又名组件) 在实体中可以定义一个嵌入式组件(embedded component), 甚至覆盖该实体中原有的列映射. 组件类必须在类一级定义@Embeddable注解. 在特定的实体 ...

  7. Hibernate 和 JPA 注解

    转载请注明:Hibernate 和 JPA 注解 | 言曌博客 1.@Entity(name="EntityName") 必须, name为可选,对应数据库中一的个表 2.@Tab ...

  8. Hibernate,JPA注解@ManyToMany_JoinTable

    可以通过@ManyToMany注解可定义的多对多关联.同时,也需要通过注解@JoinTable描述关联表和关联条件.如果是双向关联,其中一段必须定义为owner,另一端必须定义为inverse(在对关 ...

  9. Hibernate,JPA注解@SecondaryTables

    使用类一级的 @SecondaryTable或@SecondaryTables注解可以实现单个实体到多个表的映射. 使用 @Column或者 @JoinColumn注解中的table参数可指定某个列所 ...

随机推荐

  1. zookeeper节点数与watch的性能测试

    zookeeper中节点数量理论上仅受限于内存,但一个节点下的子节点数量受限于request/response 1M数据 (size of data / number of znodes) zooke ...

  2. 计算NSString含有多少个相同字符串

    // //  NSString+NSStringExt.m //  01-NSString类 // //  Created by apple on 14-3-20. //  Copyright (c) ...

  3. Alloc and release

    https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractic ...

  4. electron "Cannot find module 'dialog'", source: module.js (336)"

    打算用electron的dialog api 谁知道, 按官方api http://electron.atom.io/docs/v0.33.0/api/dialog/ https://github.c ...

  5. Eclipse+SVN搭建开发环境

    目前我们开发环境为:windows service 2008 r2 x64 现在开始记录一下eclipse+SVN环境搭建过程: 1,)下载 VisualSVN-Server-3.4.2-x64:ht ...

  6. iOS 判断字符串中含有某个字符串 rangeOfString

    //判断roadTitleLab.text 是否含有qingjoin if([roadTitleLab.text rangeOfString:@"qingjoin"].locati ...

  7. AIR 中的 File 对象 所访问的文件夹位置

    AIR 中的 File 对象 所访问的文件夹位置 Link 关于File.cacheDirectory的一点说明 According to the Apple guidelines, data tha ...

  8. 【Origin】 破阵子-未可留 征人调

    几朝岁月,悠悠,容颜改,两鬓衰,可恨荣光不留! 一生事,忧心畔,可怜惶惶,不拿年岁当缠头: 只把扑朔往往,人生几回首: 等闲识得料峭处,一腔泪流: 曾记否,三十功名尘与土,不可解忧愁: 青春换得明日花 ...

  9. Ubuntu 16.04 LTS Final Beta about JAVA

    我们知道Ubuntu里可能会事先安装了openjdk.但是我习惯于Oracle jdk. ## < 卸载 openjdk > successfully: ### Terminal comm ...

  10. [转]JVM内幕:Java虚拟机详解

    本文由 ImportNew - 挖坑的张师傅 翻译自 jamesdbloom.欢迎加入翻译小组.转载请见文末要求. 这篇文章解释了Java 虚拟机(JVM)的内部架构.下图显示了遵守Java SE 7 ...