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

 <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3307/users
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">
mysqlusers
</property>
<property name="format_sql">true</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.b510.examples.Product" />
<mapping class="com.b510.examples.Category" /> </session-factory> </hibernate-configuration>

利用Hibernate的逆向工程生成:

Category.java      and           Product.java

Category.java

 package com.b510.examples;

 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; //当前的类是一个持久化类,是Category这个类。他映射了一个表category。所对应的 数据库是users
//这句:@Table(name = "category", catalog = "users") 可以省略
@Entity
@Table(name = "category", catalog = "users") public class Category implements java.io.Serializable { private static final long serialVersionUID = 3240281547213597385L;
private Integer id;
private String name;
private String description;
private Set<Product> products = new HashSet<Product>(0); public Category() {
} public Category(String name, String description, Set<Product> products) {
this.name = name;
this.description = description;
this.products = products;
} // 主键 :@Id 主键生成方式:strategy = "increment"
//映射表中id这个字段,不能为空,并且是唯一的
@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
} public void setId(Integer id) {
this.id = id;
} //映射表中name这个字段 ,长度是500
@Column(name = "name", length = 500)
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} //映射表中description这个字段 ,长度是500
@Column(name = "description", length = 500)
public String getDescription() {
return this.description;
} public void setDescription(String description) {
this.description = description;
} //级联操作:cascade = CascadeType.ALL
//延迟加载:fetch = FetchType.LAZY
//映射:mappedBy = "category"
//一对多方式
@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

 package com.b510.examples;

 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 org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "product", catalog = "users")
public class Product implements java.io.Serializable { private static final long serialVersionUID = -1546206493725028472L;
private Integer id;
private Category category;
private String name;
private String price;
private String descripton; public Product() {
} public Product(Category category, String name, String price,
String descripton) {
this.category = category;
this.name = name;
this.price = price;
this.descripton = descripton;
} @GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
} public void setId(Integer id) {
this.id = id;
} //延迟加载:多对一方式
//关联信息:外键name = "category_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 = 500)
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} @Column(name = "price", length = 10)
public String getPrice() {
return this.price;
} public void setPrice(String price) {
this.price = price;
} @Column(name = "descripton", length = 500)
public String getDescripton() {
return this.descripton;
} public void setDescripton(String descripton) {
this.descripton = descripton;
} }

测试代码:

HibernateTest.java

 /**
*
*/
package com.b510.examples; import java.util.Set; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration; /**
*
* @author XHW
*
* @date 2011-7-20
*
*/
public class HibernateTest { public static void main(String[] args) {
HibernateTest test=new HibernateTest();
test.add();
test.find();
}
public void add(){
Configuration config=new AnnotationConfiguration();
config.configure();
SessionFactory sessionFactory=config.buildSessionFactory();
Session session=sessionFactory.getCurrentSession();
session.beginTransaction();
Category c=(Category)session.get(Category.class, 5); Product p=new Product();
p.setName("计算机科学与技术");
p.setPrice("123");
p.setDescripton("计算机科学与技术,好啊,真是红啊"); p.setCategory(c);
c.getProducts().add(p); session.save(p);
session.getTransaction().commit();
} public void find(){
Configuration config=new AnnotationConfiguration();
config.configure();
SessionFactory sessionFactory=config.buildSessionFactory();
Session session=sessionFactory.getCurrentSession();
session.beginTransaction();
Category c=(Category)session.get(Category.class, 5);
System.out.println("id: "+c.getId()+" name:"+c.getName());
Set<Product> p=c.getProducts();
for(Product product:p){
System.out.println("id:"+product.getId()+" name:"+product.getName()+" description:"+product.getDescripton());
}
session.getTransaction().commit();
}
}

运行效果:

 log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
select
category0_.id as id1_0_,
category0_.description as descript2_1_0_,
category0_.name as name1_0_
from
users.category category0_
where
category0_.id=?
Hibernate:
select
products0_.category_id as category5_1_,
products0_.id as id1_,
products0_.id as id0_0_,
products0_.category_id as category5_0_0_,
products0_.descripton as descripton0_0_,
products0_.name as name0_0_,
products0_.price as price0_0_
from
users.product products0_
where
products0_.category_id=?
Hibernate:
select
max(id)
from
product
Hibernate:
insert
into
users.product
(category_id, descripton, name, price, id)
values
(?, ?, ?, ?, ?)
Hibernate:
select
category0_.id as id5_0_,
category0_.description as descript2_5_0_,
category0_.name as name5_0_
from
users.category category0_
where
category0_.id=?
id: 5 name:xml33
Hibernate:
select
products0_.category_id as category5_1_,
products0_.id as id1_,
products0_.id as id4_0_,
products0_.category_id as category5_4_0_,
products0_.descripton as descripton4_0_,
products0_.name as name4_0_,
products0_.price as price4_0_
from
users.product products0_
where
products0_.category_id=?
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. Java的几种加载驱动的方法

    1.Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 2.DriverManager.registerD ...

  2. 8. String to Integer

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  3. [转载]AngularJS快速开始

    AngularJS快速开始 Hello World! 开始学习AngularJS的一个好方法是创建经典应用程序“Hello World!”: 使用您喜爱的文本编辑器,创建一个HTML文件,例如:hel ...

  4. 【BZOJ4866】[YNOI2017] 由乃的商场之旅(莫队)

    点此看题面 大致题意: 给你一个字符串,每次给你一段区间,问这段区间内有多少个字符串在重新排列后可以变成一个回文串. 关于莫队 详见这篇博客:莫队算法学习笔记(一)--普通莫队. 关于回文 要使一个字 ...

  5. IIS6.0开启gzip压缩

    双击IIS服务器,右键点击网站,点击属性,然后点击服务,我们看到HTTP压缩,然后在压缩应用程序文件,压缩静态文件中打钩,然后点击确定,第一步就完成了   然后我们右键点击web服务扩展,点击添加一个 ...

  6. ArrayList集合例题,商品库存管理(集合)

    创建车库集合,存进车 public class demo1 { String pinpai; String c; int s; } import java.util.ArrayList; class ...

  7. 国产中标麒麟Linux部署dotnet core 环境并运行项目 (三) 部署运行WEB API项目

    部署dotnet Core Web API 上一步的文章,是我们公司最核心的一个ORM组件,在中标麒麟系统完成了一个插入数据的任务,这一步是将正式的从dot net framework 迁移到 dot ...

  8. ES6学习(二):函数的扩展

    chapter07 函数的扩展 7.1 函数默认值 7.1.1 参数默认值简介 传统做法的弊端(||):如果传入的参数相等于(==)false的话,仍会被设为默认值,需要多加入一个if判断,比较麻烦. ...

  9. React 服务端渲染最佳解决方案

    最近在开发一个服务端渲染工具,通过一篇小文大致介绍下服务端渲染,和服务端渲染的方式方法.在此文后面有两中服务端渲染方式的构思,根据你对服务端渲染的利弊权衡,你会选择哪一种服务端渲染方式呢? 什么是服务 ...

  10. Vuex的简单了解

    vuex的官网了解:https://vuex.vuejs.org/zh/guide/ 一.什么是vuex? Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所 ...