hibernate学习笔记-01helloword

1、hibernate必备jar包

antlr-2.7.6.jar
asm.jar
c3p0-0.9.0.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
ehcache-1.2.jar
hibernate3.jar
junit-4.10.jar
log4j-1.2.11.jar

jta.jar
mysql-connector-java-5.1.14.jar

 

2、hibernate必须配置文件

hibernate.cfg.xml
log4j.properties

 

并且将这两个文件放在src目录下

 

3、通过通过Bean和hbm.xml配置文件生成数据表

Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(false, true);

 

4、实例HelloWord

(1)配置hibernate.cfg.xml文件

 

<hibernate-configuration>
	<session-factory name="foo">
		
		<!-- 数据库连接配置信息 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///hibernate_test</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		
		<!-- 数据库连接池配置信息 -->
		<property name="hibernate.c3p0.max_size">2</property>
		<property name="hibernate.c3p0.min_size">2</property>
		<property name="hibernate.c3p0.timeout">5000</property>
		<property name="hibernate.c3p0.max_statements">100</property>
		
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>

		<!-- 映射hbm.xml配置文件 -->
		<mapping resource="com/uwaysoft/hibernate/bean/Message.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

 

 (2)hbm.xml配置文件

<hibernate-mapping package="com.uwaysoft.hibernate.bean">
    <class name="Message" table="t_message">
		<id name="id">
			<!-- id自增 -->
			<generator class="increment"/>
		</id>
		<property name="text" length="100" not-null="true"/>
		<many-to-one name="nextMessage" cascade="all" column="next_id"
			foreign-key="fk_next_message"></many-to-one>
	</class>
</hibernate-mapping>

 

(3)在mysql数据库中创建数据库hibernate_test

create database hibernate_test

 

(4)自动生成数据表

	public static void schemaExport(){
		Configuration cfg = new Configuration().configure();
		SchemaExport export = new SchemaExport(cfg);
		export.create(false, true);
	}

 

 (5)保存数据

	/***
	 * sessionFactory
	 */
	private SessionFactory factory = new Configuration().configure().buildSessionFactory();
	
	/**
	 * 保存对象
	 * @param message
	 */
	public void insert(Message message){
		/** 获得session **/
		Session session = factory.openSession();
		/** 开启事务 **/
		Transaction transaction = session.beginTransaction();
		/** 保存数据 **/
		session.persist(message);
		/** 提交事务 **/
		transaction.commit();
		/** 关闭session **/
		session.close();
	}

 

 

附件:由于jar太多,上传附件中不包含jar包

你可能感兴趣的:(Hibernate)