`
fireflyjava
  • 浏览: 184541 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Hibernate3学习笔记

阅读更多
一. 使用Hibernate达到数据存储的目的
1. 新建项目Hibernate_0100_HelloWorld
	1.1 在项目下新建Student.java,包名为com.bjsxt.hibernate.model,源程序如下:
		package com.bjsxt.hibernate.model;
		
		public class Student {
			public int getId() {
				return id;
			}
			public void setId(int id) {
				this.id = id;
			}
			public String getName() {
				return name;
			}
			public void setName(String name) {
				this.name = name;
			}
			public int getAge() {
				return age;
			}
			public void setAge(int age) {
				this.age = age;
			}
			private int id;
			private String name;
			private int age;
		}
	1.2 引入相关的jar文件
		hibernate3.jar
		antlr-2.7.6.jar
		commons-collections-3.1.jar
		dom4j-1.6.1.jar
		javassist-3.9.0.GA.jar
		jta-1.1.jar
		slf4j-api-1.5.8.jar
		slf4j-nop-1.5.8.jar
2. 建立配置文件:hibernate.cfg.xml
	2.1 在src目录下新建hibernate.cfg.xml
	2.2 在Hibernate Reference Documentation找到3.Configuration下的3.7XML configuration file,点击进入
	2.3 把XML configuration file 中的内容复制到hibernate.cfg.xml中
	2.4 修改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">
		
		<hibernate-configuration>
		
		    <session-factory>
		
		        <!-- Database connection settings -->
		        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
		        <property name="connection.username">root</property>
		        <property name="connection.password">123</property>
		
		        <!-- JDBC connection pool (use the built-in) -->
		        <!--<property name="connection.pool_size">1</property>-->
		
		        <!-- SQL dialect -->
		        <property name="dialect">org.hibernate.dialect.MySQLDialect</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.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 resource="com/bjsxt/hibernate/model/Student.hbm.xml"/>
		    </session-factory>
		
		</hibernate-configuration>
3. 建立映射文件Student.hbm.xml
	3.1 在包下新建Student.hbm.xml
	3.2 在Hibernate Reference Documentation下找到1.1.3 The mapping file
	3.3 把The mapping file中的内容复制到Student.hbm.xml中
	3.4 修改其中的内容,如下:
		<?xml version="1.0"?>
		<!DOCTYPE hibernate-mapping PUBLIC
		        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
		        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
		
		<hibernate-mapping package="com.bjsxt.hibernate.model">
			<class name="Student" table="student">
				<id name="id" column="id"> </id>
				<property name="name"></property>
				<property name="age"></property>
			</class>
		
		</hibernate-mapping>
	3.5 把映射文件注册到配置文件hibernate.cfg.xml中
4. 建立测试类
	4.1 在包下新建StudentTest.java,代码如下:
		package com.bjsxt.hibernate.model;
		
		import org.hibernate.Session;
		import org.hibernate.SessionFactory;
		import org.hibernate.cfg.Configuration;
		
		public class StudentTest {
		
			public static void main(String[] args) {
				Student s = new Student();
				s.setId(1);
				s.setName("s1");
				s.setAge(1);
				
				Configuration cfg = new Configuration();
				SessionFactory sf = cfg.configure().buildSessionFactory();
				Session session = sf.openSession();
				session.beginTransaction();
				session.save(s);
				session.getTransaction().commit();
				session.close();
				sf.close();
			}
		}
5. 在MySQL中建立数据库和相应的表
		create database hibernate;
		use hibernate;
		create table student(id int primary key,name varchar(20),age int);
6. 插入数据
	6.1 运行StudentTest.java
	6.2 在MySql中输入select * from student查看结果
		id	name	age
		1	s1	1
=====================================================================
=====================================================================
二. 使用Annotation实现数据的储存
1. 引入相关jar文件
	hibernate-annotations.jar
	ejb3-persistence.jar
	hibernate-commons-annotations.jar
2. 在com.bjsxt.hibernate.model下新建Teacher.java,代码如下:
	package com.bjsxt.hibernate.model;
	
	import javax.persistence.Entity;
	import javax.persistence.Id;
	
	@Entity
	public class Teacher {
		private int id;
		private String name;
		private String title;
		
		@Id
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getTitle() {
			return title;
		}
		public void setTitle(String title) {
			this.title = title;
		}
	}
3. 修改配置文件hibernate.cfg.xml
	3.1 把<mapping class="com.bjsxt.hibernate.model.Teacher"/>加入到<session-factory></session-factory>中
		<?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">
		
		<hibernate-configuration>
		
		    <session-factory>
		
		        <!-- Database connection settings -->
		        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
		        <property name="connection.username">root</property>
		        <property name="connection.password">123</property>
		
		        <!-- JDBC connection pool (use the built-in) -->
		        <!--<property name="connection.pool_size">1</property>-->
		
		        <!-- SQL dialect -->
		        <property name="dialect">org.hibernate.dialect.MySQLDialect</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.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 resource="com/bjsxt/hibernate/model/Student.hbm.xml"/>
		        <mapping class="com.bjsxt.hibernate.model.Teacher"/>
		    </session-factory>
		
		</hibernate-configuration>
4. 建立测试类
	4.1 在包下新建TeacherTest.java文件,代码如下:
		package com.bjsxt.hibernate.model;
		
		import org.hibernate.Session;
		import org.hibernate.SessionFactory;
		import org.hibernate.cfg.AnnotationConfiguration;
		import org.hibernate.cfg.Configuration;
		
		public class TeacherTest {
		
			public static void main(String[] args) {
				Teacher t = new Teacher();
				t.setId(1);
				t.setName("t1");
				t.setTitle("中级");
				
				Configuration cfg = new AnnotationConfiguration();
				SessionFactory sf = cfg.configure().buildSessionFactory();
				Session session = sf.openSession();
				session.beginTransaction();
				session.save(t);
				session.getTransaction().commit();
				session.close();
				sf.close();
			}
		}
5. 在MySQL中建立数据库和相应的表
		create database hibernate;
		use hibernate;
		create table teacher(id int primary key,name varchar(20),title varchar(10));
6. 插入数据
	6.1 运行TeacherTest.java
	6.2 在MySql中输入select * from teacher查看结果
		id	name	title
		1	t1	中级
===============================================================
===============================================================
三. O/R Mapping Frameworks
1. hibernate
2. toplink
3. jdo
4. ibatis
5. JPA
===============================================================
===============================================================
四. Hibernate基础配置
1. hibernate.cfg.xml 配置文件中<property name="hbm2ddl.auto">create</property>的取值如下:
	validate	update	create	create-drop
2. 在实际工作中,先建表后建实现类
3. 搭建Log4J日志环境
	3.1 加入如下几个jar包
		slf4j-api-1.5.8.jar
		slf4j-log4j12-1.5.8.jar
		log4j-1.2.15.jar
	3.2 把log4j.properties复制到src文件下的包里,设置如下:
		### direct log messages to stdout ###
		log4j.appender.stdout=org.apache.log4j.ConsoleAppender
		log4j.appender.stdout.Target=System.out
		log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
		log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
		
		log4j.rootLogger=warn, stdout
		
		### log schema export/update ###
		log4j.logger.org.hibernate.tool.hbm2ddl=debug
4. 搭建Junit日志环境
	4.1 新建一个名为MyJunit的User Libraries,把junit-4.7.jar加入其中
5. hibernate.cfg.xml中的两项配置
	5.1 <property name="show_sql">true</property>  表示显示SQL语句
	5.2 <property name="format_sql">true</property>  格式化SQL语句
6. 表名和类名不同,对表名进行配置
	6.1 Annotion: @Table
	6.1.1 示例:
		@Entity
		@Table(name="_Teacher")
		public class Teacher {	}     /*对应到数据库中的_Teacher表*/
	
	6.2 xml: 修改Student.hbm.xml文件
	6.2.1 示例:
		<hibernate-mapping package="com.bjsxt.hibernate.model">
			<class name="Student" table="_student">
				<id name="id"> </id>
				<property name="name"></property>
				<property name="age"></property>
			</class>
		
		</hibernate-mapping>
7. 字段名和属性相同
	7.1 默认为@Basic
	7.2 xml中不用写column
8. 字段名和属性名不同
	8.1 Annotation:@Column
	8.1.1 示例:
		@Column(name="_name")
		public String getName() {
			return name;
		}
	8.2 xml:自己查询
9. 不需要的字段
	9.1 在字段的get方法上加注解@Transient
10. 时间精度
	10.1 Annotation
		@Temporal(TemporalType.DATE)
		public Date getBirthDate() {
			return birthDate;
		}
	10.2 XML	
		<property name=birthDate type="date"></property>
11. 枚举类型
	11.1 Annotation
		@Enumerated(EnumType.STRING)
		@Enumerated(EnumType.ORDINAL)
===============================================================
===============================================================
五. ID生成策略
1. 自定义ID(如上)
2. AUTO
	2.1 默认:对MySQL使用auto_increment; 对Oracle使用hibernate_sequence(名称固定)
	2.2 取值如下:
		increment: 用于为long, short或者int 类型生成唯一标识。只有在没有其他进程往同一张表中插入数据时才能使用。在集群下不要使用
		identity: 对DB2,MySQL,MS SQL Server,Sybase和HypersonicSQL的内置标识字段提供支持。返回的标识符是long,short,或者int类型
		sequence: 在DB2,PostgreSQL,Oracle,SAP DB,Mckoi中使用序列(sequence),而在Interbase中使用生成器(generator).返回的标识符是long,short或者int类型的。
		uuid: uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network(the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.
		native: selects identity,sequence or hilo depending upon the capabilities of the underlying database. 
	2.3 示例:修改Student.hbm.xml文件如下
		<?xml version="1.0"?>
		<!DOCTYPE hibernate-mapping PUBLIC
		        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
		        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
		
		<hibernate-mapping>
			<class name="com.bjsxt.hibernate.Student">
				
					
				<id name="id">
					<generator class="uuid"></generator>
				</id>
				
				<property name="age" />
				<property name="sex" />
				<property name="good" type="yes_no"></property>
		    </class>
			
		</hibernate-mapping>
3. 使用Anotation自动生成ID
	3.1 在getId()方法前加@GeneratedValue
		@Entyty 
		//@SequenceGenerator(name="teacherSEQ", sequenceName="teacherSEQ_DB")
		public class Teacher {
		...
		@Id
		@GeneratedValue
		//@GeneratedValue(strategy=GenerationType.IDENTITY)    用于Mysql数据库
		//@GeneratedValue(strategy=GenerationType.SEQUENCE)
		//@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="teacherSEQ")
		public int getId() {
			return id;
		}
		...
		}
	3.2 使用表生成主键
		@Entyty
		@javax.persistense.TableGenerator (
			name="Teacher_GEN",
			table="GENERATOR_TABLE",
			pkColumnName="pk_key",
			valueColumnName="pk_value",
			pkColumnValue="Teacher",
			allocationSize=1
		)
4. 联合主键
	4.1 在Student.hbm.xml中使用composite-id,重写equals和hashCode,实现serializable
		<hibernate-mapping>
			<class name="com.bjsxt.hibernate.Student">		
				<composite-id name="pk" class="com.bjsxt.hibernate.StudentPK">
					<key-property name="id"></key-property>
					<key-property name="name"></key-property>
				</composite-id>
				
				<property name="age" />
				<property name="sex" />
				<property name="good" type="yes_no"></property>
		    </class>	
		</hibernate-mapping>
		@Override
		public boolean equals(Object o) {
			if(o instanceof TeacherPK) {
				TeacherPK pk = (TeacherPK)o;
				if(this.id == pk.getId() && this.name.equals(pk.getName())) {
					return true;
				}
			}
			return false;
		}
			
		@Override
		public int hashCode() {
			return this.name.hashCode();
		}
	4.2 联合主键(Annotation)
		4.2.1 将组件类注解为@Embeddable,并将组件的属性注解为@Id
		4.2.2 将组件的属性注解为@EmbeddedId
		4.2.3 将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics