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. SecureCRT rz和sz命令不可用,安装lrzsz

    1.从网站下载 lrzsz-x.xx.xx.tar.gz2.解压文件[root@localhost src]# tar zxvf lrzsz-0.12.20.tar.gz3.安装[root@local ...

  2. jquery-ui 进度条

    <!DOCTYPE html> <html> <head> <meta charset="utf8" /> <title> ...

  3. wddm 部署问题解决

    在把wddm部署到一台老的服务上的 windows server 2003 上时遇到了问题,之前也在 windows server 2003 上装过,但是并没有遇到问题,估计和服务器比较老有关系. 问 ...

  4. spark streaming 实现接收网络传输数据进行WordCount功能

    package iie.udps.example.operator.spark; import scala.Tuple2; import org.apache.spark.SparkConf; imp ...

  5. UI学习笔记---第五天

    target...action设计模式   代理设计模式   手势识别器 target...action设计模式 耦合是衡量一个程序写的好坏的标准之一,耦合是衡量模块与模块之间关联程度的指标 &quo ...

  6. UVa 1585 Score --- 水题

    题目大意:给出一个由O和X组成的串(长度为1-80),统计得分. 每个O的分数为目前连续出现的O的个数,例如,OOXXOXXOOO的得分为1+2+0+0+1+0+0+1+2+3 解题思路:用一个变量t ...

  7. SVN代码提交冲突解决方案

    SVN代码提交冲突解决方案 1.若你的代码被其他人修改并提交过了,期间你自己也修改过该文件,UPDATE的时候自己代码被覆盖. 右键——>显示日志 查看该文件的更新记录 找到需恢复的版本 右键— ...

  8. poj2186 强连通

    题意:有 n 头牛,以及一些喜欢关系,牛 A 喜欢牛 B,这种关系可以传递,问有多少头牛被牧场上所有牛喜欢. 首先强连通,因为在同一个强连通分量中牛是等价的,然后对于一个有向无环图看是否只有一个强连通 ...

  9. MySQL中日期与字符串相互转换,并进行日期比较查询

    技术交流群:233513714 1.日期无需转换查询(日期在数据库中的类型为字符串) select * from day where dateTime > '2016-03-15' 2.使用da ...

  10. 用Socket做一个局域网聊天工具(转)

    原文:http://www.cnblogs.com/technology/archive/2010/08/15/1799858.html 程序设计成为简单的服务端和客户端之间的通信, 但通过一些方法可 ...