Hibernate环境搭建

1、导入jar包

hibernate.jar 
antlr-2.7.6.jar 
commons-collections-3.1.jar 
jta-1.1.jar 
dom4j-1.6.1.jar
javassist-3.4.GA.jar 
slf4j-api-1.5.2.jar 
slf4j-log4j12-1.5.2.jar 
如果使用C3P0数据源实现数据库连接:c3p0-0.9.0.4.jar 
如果使用mysql数据库,Mysql JDBC驱动: mysql-connector.jar

2、写配置文件

建立一个User实体类,测试用。

package cn.itcast.hibernate.domain;

import java.util.Date;

public class User {
	private long id;
	private String name;
	private Date birthday;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

}

写User.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 package="cn.itcast.hibernate.domain">

	<class name="User" table="itcast_user">
		<id name="id">
			<generator class="native" />
		</id>
		<property name="name" />
		<property name="birthday" />
	</class>

</hibernate-mapping>

写Hibernate主配置文件hibernate.cfg.xml

<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

	<session-factory>

		<!-- 1,数据库连接信息 -->
		<property name="dialect">
			org.hibernate.dialect.MySQL5InnoDBDialect
		</property>
		<property name="connection.url">jdbc:mysql:///rowsy</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>

		<!-- 2,其他配置 -->
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">update</property>

		<!-- 3,导入映射文件 -->
		<mapping resource="cn/itcast/hibernate/domain/User.hbm.xml" />


	</session-factory>

</hibernate-configuration>

3、测试

写一个测试类:

package cn.itcast.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import cn.itcast.hibernate.domain.User;

public class Base {

	public static void main(String[] args) {
		SessionFactory sessionFactory = new Configuration().configure()
				.buildSessionFactory();
		Session session = sessionFactory.openSession();
		
		User user = new User();
		user.setBirthday(new Date());
		user.setName("ronnie");

		Transaction transaction=session.beginTransaction();
		session.save(user);
		transaction.commit();
		
		session.close();
	}

}

4、运行成功!

Hibernate环境搭建,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。