日期:2014-05-16  浏览次数:20706 次

《mysql使用hibernate入门案例》
//User.java


package com.fenghuo.domain;

public class User {

	private Integer id;
	private String username;
	private String password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

<!-- User.hbm.xml -->

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 该文件用于配置,domain跟表的映射关系 -->
<hibernate-mapping package="com.fenghuo.domain">
	<class name="User" table="user">
	<!-- id元素用于指定主键属性 -->
	<id name="id" column="id" type="java.lang.Integer">
	<!-- 用于指定主键生成策略 -->
	<generator class="native"></generator>
	</id>
	<!-- 对其他属性进行配置 -->
	<property name="username" type="java.lang.String">
	<column name="username" not-null="false"></column>
	</property>
	<property name="password" type="java.lang.String">
	<column name="password" not-null="false"></column>
	</property>
	</class>
</hibernate-mapping>

<!-- 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>
	<!-- 配置使用的driver -->
	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="connection.username">root</property>
	<property name="connection.password">123</property>
	<property name="connection.url">jdbc:mysql:///test</property>
	<!-- 告诉hibernate用的那种数据库 -->
	<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
	<!-- 显示出对应的sql语句 -->
	<property name="show_sql">true</property>
	<!-- 指定对象管理映射文件 -->
	<mapping resource="com/fenghuo/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

//TestMain.java


package com.fenghuo.view;

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

import com.fenghuo.domain.User;

public class TestMain {

	public static void main(String[] args) {
		//1.创建Configuration,该对象用于读取hibernate.cfg.xml,并完成初始化
		Configuration configuration = new Configuration().configure();
		//2.创建SessionFactory[是一个会话工厂,是一个重量级的类]
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//3.创建Session
		Session session = sessionFactory.openSession();
		//4.使用事务提交
		Transaction transaction = session.beginTransaction();
		
		//添加一个用户
		User user = new User();
		user.setUsername("fenghuo");
		user.setPassword("123");
		
		session.save(user);
		transaction.commit();
		session.close();
	}

}

文件结构: