Hibernate Annotation   (Hibernate 注解)

 

进入:http://www.hibernate.org

说明文档:

英文:http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/

中文:http://docs.jboss.org/hibernate/annotations/3.4/reference/zh_cn/html_single/

下载:hibernate annotation 3.4.0 GA

得到:hibernate-annotations.jar

   hibernate-commons-annotation.jar

   ejb3-persistence.jar

数据库:mysql

category表:id,name,description       <Pk>id

product表:id,name ,price, description ,category_id                  <pk>id  <fk>category_id

新建java project项目:

Add Hibernate Capabilities

hibernate.cfg.xml

  1. <?xml version='1.0' encoding='UTF-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5.  
  6. <!-- Generated by MyEclipse Hibernate Tools. -->
  7. <hibernate-configuration>
  8.  
  9. <session-factory>
  10. <property name="dialect">
  11. org.hibernate.dialect.MySQLDialect
  12. </property>
  13. <property name="connection.url">
  14. jdbc:mysql://localhost:3307/users
  15. </property>
  16. <property name="connection.username">root</property>
  17. <property name="connection.password">root</property>
  18. <property name="connection.driver_class">
  19. com.mysql.jdbc.Driver
  20. </property>
  21. <property name="myeclipse.connection.profile">
  22. mysqlusers
  23. </property>
  24. <property name="format_sql">true</property>
  25. <property name="show_sql">true</property>
  26. <property name="current_session_context_class">thread</property>
  27. <mapping class="com.b510.examples.Product" />
  28. <mapping class="com.b510.examples.Category" />
  29.  
  30. </session-factory>
  31.  
  32. </hibernate-configuration>

利用Hibernate的逆向工程生成:

Category.java      and           Product.java

Category.java

  1. package com.b510.examples;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5.  
  6. // 标准注解
  7.  
  8. import javax.persistence.CascadeType;
  9. import javax.persistence.Column;
  10. import javax.persistence.Entity;
  11. import javax.persistence.FetchType;
  12. import javax.persistence.GeneratedValue;
  13. import javax.persistence.Id;
  14. import javax.persistence.OneToMany;
  15. import javax.persistence.Table;
  16.  
  17. //增加的注解
  18.  
  19. import org.hibernate.annotations.GenericGenerator;
  20.  
  21. //当前的类是一个持久化类,是Category这个类。他映射了一个表category。所对应的 数据库是users
  22. //这句:@Table(name = "category", catalog = "users") 可以省略
  23. @Entity
  24. @Table(name = "category", catalog = "users")
  25.  
  26. public class Category implements java.io.Serializable {
  27.  
  28. private static final long serialVersionUID = 3240281547213597385L;
  29. private Integer id;
  30. private String name;
  31. private String description;
  32. private Set<Product> products = new HashSet<Product>(0);
  33.  
  34. public Category() {
  35. }
  36.  
  37. public Category(String name, String description, Set<Product> products) {
  38. this.name = name;
  39. this.description = description;
  40. this.products = products;
  41. }
  42.  
  43. // 主键 :@Id 主键生成方式:strategy = "increment"
  44. //映射表中id这个字段,不能为空,并且是唯一的
  45. @GenericGenerator(name = "generator", strategy = "increment")
  46. @Id
  47. @GeneratedValue(generator = "generator")
  48. @Column(name = "id", unique = true, nullable = false)
  49. public Integer getId() {
  50. return this.id;
  51. }
  52.  
  53. public void setId(Integer id) {
  54. this.id = id;
  55. }
  56.  
  57. //映射表中name这个字段 ,长度是500
  58. @Column(name = "name", length = 500)
  59. public String getName() {
  60. return this.name;
  61. }
  62.  
  63. public void setName(String name) {
  64. this.name = name;
  65. }
  66.  
  67. //映射表中description这个字段 ,长度是500
  68. @Column(name = "description", length = 500)
  69. public String getDescription() {
  70. return this.description;
  71. }
  72.  
  73. public void setDescription(String description) {
  74. this.description = description;
  75. }
  76.  
  77. //级联操作:cascade = CascadeType.ALL
  78. //延迟加载:fetch = FetchType.LAZY
  79. //映射:mappedBy = "category"
  80. //一对多方式
  81. @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "category")
  82. public Set<Product> getProducts() {
  83. return this.products;
  84. }
  85.  
  86. public void setProducts(Set<Product> products) {
  87. this.products = products;
  88. }
  89.  
  90. }

Product.java

  1. package com.b510.examples;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.FetchType;
  6. import javax.persistence.GeneratedValue;
  7. import javax.persistence.Id;
  8. import javax.persistence.JoinColumn;
  9. import javax.persistence.ManyToOne;
  10. import javax.persistence.Table;
  11. import org.hibernate.annotations.GenericGenerator;
  12.  
  13. @Entity
  14. @Table(name = "product", catalog = "users")
  15. public class Product implements java.io.Serializable {
  16.  
  17. private static final long serialVersionUID = -1546206493725028472L;
  18. private Integer id;
  19. private Category category;
  20. private String name;
  21. private String price;
  22. private String descripton;
  23.  
  24. public Product() {
  25. }
  26.  
  27. public Product(Category category, String name, String price,
  28. String descripton) {
  29. this.category = category;
  30. this.name = name;
  31. this.price = price;
  32. this.descripton = descripton;
  33. }
  34.  
  35. @GenericGenerator(name = "generator", strategy = "increment")
  36. @Id
  37. @GeneratedValue(generator = "generator")
  38. @Column(name = "id", unique = true, nullable = false)
  39. public Integer getId() {
  40. return this.id;
  41. }
  42.  
  43. public void setId(Integer id) {
  44. this.id = id;
  45. }
  46.  
  47. //延迟加载:多对一方式
  48. //关联信息:外键name = "category_id"
  49. @ManyToOne(fetch = FetchType.LAZY)
  50. @JoinColumn(name = "category_id")
  51. public Category getCategory() {
  52. return this.category;
  53. }
  54.  
  55. public void setCategory(Category category) {
  56. this.category = category;
  57. }
  58.  
  59. @Column(name = "name", length = 500)
  60. public String getName() {
  61. return this.name;
  62. }
  63.  
  64. public void setName(String name) {
  65. this.name = name;
  66. }
  67.  
  68. @Column(name = "price", length = 10)
  69. public String getPrice() {
  70. return this.price;
  71. }
  72.  
  73. public void setPrice(String price) {
  74. this.price = price;
  75. }
  76.  
  77. @Column(name = "descripton", length = 500)
  78. public String getDescripton() {
  79. return this.descripton;
  80. }
  81.  
  82. public void setDescripton(String descripton) {
  83. this.descripton = descripton;
  84. }
  85.  
  86. }

测试代码:

HibernateTest.java

  1. /**
  2. *
  3. */
  4. package com.b510.examples;
  5.  
  6. import java.util.Set;
  7.  
  8. import org.hibernate.Session;
  9. import org.hibernate.SessionFactory;
  10. import org.hibernate.cfg.AnnotationConfiguration;
  11. import org.hibernate.cfg.Configuration;
  12.  
  13. /**
  14. *
  15. * @author XHW
  16. *
  17. * @date 2011-7-20
  18. *
  19. */
  20. public class HibernateTest {
  21.  
  22. public static void main(String[] args) {
  23. HibernateTest test=new HibernateTest();
  24. test.add();
  25. test.find();
  26. }
  27. public void add(){
  28. Configuration config=new AnnotationConfiguration();
  29. config.configure();
  30. SessionFactory sessionFactory=config.buildSessionFactory();
  31. Session session=sessionFactory.getCurrentSession();
  32. session.beginTransaction();
  33. Category c=(Category)session.get(Category.class, 5);
  34.  
  35. Product p=new Product();
  36. p.setName("计算机科学与技术");
  37. p.setPrice("123");
  38. p.setDescripton("计算机科学与技术,好啊,真是红啊");
  39.  
  40. p.setCategory(c);
  41. c.getProducts().add(p);
  42.  
  43. session.save(p);
  44. session.getTransaction().commit();
  45. }
  46.  
  47. public void find(){
  48. Configuration config=new AnnotationConfiguration();
  49. config.configure();
  50. SessionFactory sessionFactory=config.buildSessionFactory();
  51. Session session=sessionFactory.getCurrentSession();
  52. session.beginTransaction();
  53. Category c=(Category)session.get(Category.class, 5);
  54. System.out.println("id: "+c.getId()+" name:"+c.getName());
  55. Set<Product> p=c.getProducts();
  56. for(Product product:p){
  57. System.out.println("id:"+product.getId()+" name:"+product.getName()+" description:"+product.getDescripton());
  58. }
  59. session.getTransaction().commit();
  60. }
  61. }

运行效果:

  1. log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
  2. log4j:WARN Please initialize the log4j system properly.
  3. Hibernate:
  4. select
  5. category0_.id as id1_0_,
  6. category0_.description as descript2_1_0_,
  7. category0_.name as name1_0_
  8. from
  9. users.category category0_
  10. where
  11. category0_.id=?
  12. Hibernate:
  13. select
  14. products0_.category_id as category5_1_,
  15. products0_.id as id1_,
  16. products0_.id as id0_0_,
  17. products0_.category_id as category5_0_0_,
  18. products0_.descripton as descripton0_0_,
  19. products0_.name as name0_0_,
  20. products0_.price as price0_0_
  21. from
  22. users.product products0_
  23. where
  24. products0_.category_id=?
  25. Hibernate:
  26. select
  27. max(id)
  28. from
  29. product
  30. Hibernate:
  31. insert
  32. into
  33. users.product
  34. (category_id, descripton, name, price, id)
  35. values
  36. (?, ?, ?, ?, ?)
  37. Hibernate:
  38. select
  39. category0_.id as id5_0_,
  40. category0_.description as descript2_5_0_,
  41. category0_.name as name5_0_
  42. from
  43. users.category category0_
  44. where
  45. category0_.id=?
  46. id: 5 name:xml33
  47. Hibernate:
  48. select
  49. products0_.category_id as category5_1_,
  50. products0_.id as id1_,
  51. products0_.id as id4_0_,
  52. products0_.category_id as category5_4_0_,
  53. products0_.descripton as descripton4_0_,
  54. products0_.name as name4_0_,
  55. products0_.price as price4_0_
  56. from
  57. users.product products0_
  58. where
  59. products0_.category_id=?
  60. id:9 name:计算机科学与技术 description:计算机科学与技术,好啊,真是红啊

hibernate注解配置举例说明的更多相关文章

  1. 。。。Hibernate注解配置的注意事项。。。

    今天本来打算录视频的,突然遇到一个拦路虎,Hibernate注解配置,有一个注意点:要么都在属性上面注解配置,要么都在getXX()方法上面用注解配置,要不然就会报错: Caused by: org. ...

  2. Hibernate注解配置

    在之前的第一次对框架的实际应用中,我使用的是Hibernate的xml配置方法,xml配置方法非常繁琐, 还是推荐所有使用Hibernate的人使用注解方式进行配置,在这篇文章中,我将列举出我们常用的 ...

  3. Hibernate注解配置与XML配置区别

    注解配置的方式与xml很很多类似: 首先是需要加入4个jar包:hibernate-commons-annotations.jar . hibernate-annotations.jar.ejb3-p ...

  4. hibernate 注解配置<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/X

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  5. 【maven + hibernate(注解) +spring +springMVC】 使用maven搭建项目

    研究,百度,查资料+好友帮助,使用MyEcplise2015工具,通过maven搭建hibernate+springMVC+spring的项目,数据库采用MySql5.5 不过使用的版本会在项目搭建过 ...

  6. 用户、角色、权限三者多对多用hibernate的一对多注解配置

    用户.角色.权限三者多对多用hibernate的一对多注解配置 //权限表@Table(name = "p")public class P { @Id @GeneratedValu ...

  7. Mingyang.net:注解配置Hibernate时报错Unknown Entity

    注解配置时报错:org.hibernate.MappingException: Unknown entity: net.mingyang.cms.bean.User org.hibernate.Map ...

  8. Hibernate 注解时 hibernate.hbm.xml的配置方法 以及与SSH整合里的配置方式

    ①纯Hibernate开发: 当你在Bean中写入注解后,需要告诉hibernate哪些类使用了注解. 方法是在hibernate.hbm.xml文件中配置 <!DOCTYPE hibernat ...

  9. spring与hibernate整合配置基于Annotation注解方式管理实务

    1.配置数据源 数据库连接基本信息存放到properties文件中,因此先加载properties文件 <!-- jdbc连接信息 --> <context:property-pla ...

随机推荐

  1. webpack最简单的入门教程里bundle.js之运行单步调试的原理解析

    读这篇文章的朋友,请确保对webpack有最基础的认识. 您可以阅读我前一篇文章:Webpack 10分钟入门 来在本地运行一个Webpack的hello world项目.https://www.to ...

  2. JavaScript:理解Promise方法

    什么是promise? Promise的核心思想是代表异步操作的一个结果,并且promise具有三个状态(pending初始状态,fulfilled成功状态,rejected失败状态).我们可以理解为 ...

  3. preprocessing MinMaxScaler

    import numpy as npfrom sklearn.preprocessing import MinMaxScalerdataset = np.array([1,2,3,5]).astype ...

  4. Python中的集合set

    >>> help(set) Help on class set in module __builtin__: class set(object) | set(iterable) -- ...

  5. JMeter接口压力测试课程入门到高级实战

    章节一压力测试课程介绍 1.2018年亿级流量压测系列之Jmeter4.0课程介绍和效果演示 简介: 讲解课程安排,使用的Jmeter版本 讲课风格:涉及的组件,操作配置多,不会一次性讲解,会先讲部分 ...

  6. Oracle ORA-01722 无效数字

    ORA-01722 无效数字 以下几种情况,数据库会报“ORA-01722 无效数字”错误: ① 对于两个类型不一致,一个“数字类型”,一个“非数字类型”进行赋值,或者比较操作: ② to_numbe ...

  7. Hotkeys.js 2.0.2 发布,JS 网页快捷键设置,捕获键盘输入和输入的组合键快捷键,它没有依赖

    这是一个强健的 Javascript 库用于捕获键盘输入和输入的组合键,它没有依赖,压缩只有只有(~3kb),gzip:1.9k. 更新内容: 添加测试用例: 添加更多特殊键支持: 修复bug. __ ...

  8. Linux基础-Linux常用命令

    Linux(/'lainʌks/)系统特点:稳定,安全,开源(一切皆文件) 装上SSH协议就可以连接Linux 装虚拟机(SSH) win用xshell工具 Linux命令:每日一个linux命令 p ...

  9. Nodejs NPM CNPM优雅安装install

    由于npm和cnpm都能安装组件,安装的组件有的保存在c盘用户目录的Appdata隐藏目录下,有的保存在安装node的目录下,而且安装在c盘的话,重装系统又得重新部署,甚是麻烦,所以这里提供优雅安装的 ...

  10. PHP面向对象编程(1)基础

    一.面向对象OOP(Oriented Object Programming) 面向过程的编程 将要实现的功能描述为一个从一开始到结束的连续的“步骤(过程)”. 一次逐步完成这些步骤.如果步骤比较大,又 ...