说明文档:
英文: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
35 public Category() {
36 }
37
38 public Category(String name, String description, Set<Product> products) {
39 this.name = name;
40 this.description = description;
41 this.products = products;