Hibernate使用Annotations最简单例子:

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1/testdb</property>
<property name="connection.username">root</property>
<property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property> <!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property> <!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property> <mapping class="com.my.bean.User"/> </session-factory> </hibernate-configuration>

HibernateUtil.java

package com.my.dao.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
return configuration.configure().buildSessionFactory(
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
} }

POJO

package com.my.bean;

import java.util.Date;

import javax.persistence.*;

@Entity
@Table(name="user")
public class User {
@Id @GeneratedValue @Column(name="user_id", nullable=false)
private long userID; @Column(name="user_name", length=100, nullable=false)
private String userName; @Column(name="create_time", nullable=false)
private Date createTime; public long getUserID() {
return userID;
} public void setUserID(long userID) {
this.userID = userID;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}

Test:

package com.my.init;
import java.util.Date; import org.hibernate.Session;
import org.hibernate.Transaction; import com.my.bean.User;
import com.my.dao.util.HibernateUtil; public class Test { public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction(); try {
User user = new User();
user.setUserName("Robin");
user.setCreateTime(new Date()); session.save(user); tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} session.close();
} }

参考文献:

http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm

[Hibernate] - Annotations的更多相关文章

  1. [Hibernate] - Annotations - Many To Many

    Hibernate annotation 多对多: 下面测试例子会自动生成一张表:card,这张是bank和user表的映射表.里头是bank_id和user_id两个组合字段. 如果想在这张映射表中 ...

  2. [Hibernate] - Annotations - One To One

    Hibernate annotation 一对一的两种实现: 1)幅表中有主表的主键ID做为引用 2)幅表的主键即为主表的ID hibernate.cfg.xml <?xml version=& ...

  3. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-007UserTypes的用法(@org.hibernate.annotations.Type、@org.hibernate.annotations.TypeDefs、CompositeUserType、DynamicParameterizedType、、、)

    一.结构 二.Hibernate支持的UserTypes接口  UserType —You can transform values by interacting with the plain JD ...

  4. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-005控制类型映射(Nationalized、@LOB、@org.hibernate.annotations.Type)

    一.简介 1. 2. 3. 4. to override this default mapping. The JPA specification has a convenient shortcut a ...

  5. java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataProvider

    Caused by: java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/MetadataProvi ...

  6. BAE 环境下 hibernate annotations 配置

     annotations 配置 首先需要加入 hibernate-jpa-2.0-api-1.0.1.Final.jar 和 ejb3-persistence.jar 这两个包 ejb3-persis ...

  7. Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataPro

    1.错误描述 信息: MLog clients using java 1.4+ standard logging. 2014-7-12 19:29:20 com.mchange.v2.c3p0.C3P ...

  8. Hibernate Annotations 注解

    Hibernate Annotations 注解 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么 ...

  9. [Hibernate] - Annotations - One To Many

    Hibernate使用Annotation的一对多: hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8&q ...

随机推荐

  1. 世纪互联运营的Microsoft Azure正式支持FreeBSD虚拟机镜像

    自2012年开始,微软云计算与企业事业部和Citrix思杰,NetApp达成合作,共同开发出第一版针对Hyper-V虚拟设备驱动以及相关的用户态程序,并将此称之为集成服务(Integration Se ...

  2. windows 任务栏图标宽度固定

    这个需要修改注册表. win+r regedit ->enter 找到以下项 HKEY_CURRENT_USER-Control Panel-Desktop-WindowsMetrics 新建字 ...

  3. c 深度剖析 6

    函数的编码风格 1.注释 2,空行 3,缩进 4,参数长度,代码长度,语句长度要合适. 5,少用全局变量 6,指针仅作输入参数时,可用const 设置其为只读属性,避免其在函数中被修改. 7,函数默认 ...

  4. Websphere发布时遇到的问题

    在发布时遇到了data source配置的问题,搞了好久没搞定,最后问题出现在 JDBC providers那边,Implementation class name 改成: com.ibm.db2.j ...

  5. Android——进度对话框

    java类代码: //普通进度对话框 public void bt8_onClick(View v) { final ProgressDialog progressDialog = new Progr ...

  6. P364 实战练习(多线程)

    尝试定义一个继承Thread类的类,并覆盖run( )方法,在run( )方法中每隔1000毫秒打印一句话. 编写代码如下: 编写PractiseThread类: package org.hanqi. ...

  7. hihoCoder#1055 : 刷油漆 (树形DP+01背包)

    题目大意:给一棵带点权的树,现在要从根节点开始选出m个连通的节点,使总权值最大. 题目分析:定义状态dp(u,m)表示在以u为根的子树从根节点开始选出m个点连通的最大总权值,则dp(u,m)=max( ...

  8. Kali linux渗透测试的艺术 思维导图

    Kali Linux是一个全面的渗透测试平台,其自带的高级工具可以用来识别.检测和利用目标网络中未被发现的漏洞.借助于Kali Linux,你可以根据已定义的业务目标和预定的测试计划,应用合适的测试方 ...

  9. 【P1813】8的倍数

    容斥原理,居然没想到……要补一下数论了 原题: 小x最近对数字8很感兴趣,有8进制,2008奥运会之类的.现在小x想知道,在[x,y]区间里,有多少个数能被8整除.小y觉得题目太简单,于是给出n个其他 ...

  10. 点亮LED(库函数实现)

    本次测试采用的芯片是STM32F103CB 我的开发板如下: 此开发板有8个led,分别为D11,D12,D13,D14,D15,D16,D17,D18.查询核心板的电路图后知道其对应芯片的控制引脚为 ...