实例-用户登录注册(Hibernate版)
-配置Hibernate
*既然Hibernate底层也是JDBC,那么也需要加载驱动
mysql-connector-java-5.0.3-bin.jar
*加载Hibernate jar文件
Hibernate工程需要的最小jar文件集合
*创建Hibernate配置文件
*可以是XML格式的
*也可以是.properties的属性文件
*Hibernate默认加载的是hibernate.cfg.xml或者是hibernate.properties
有一个xml文件与JavaBean中的类对应
<?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" >
<hibernate-mapping>
<class name="com.amaker.bean.User" table="UserTbl">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></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>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db</property>
<property name="connection.username">root</property>
<property name="connection.password">1</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="com/amaker/bean/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
创建一个工具类HibernateUtil
内容如下:
package com.amaker.zhaofei;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public Session getSession() {
Configuration conf = new Configuration();
conf.configure();
SessionFactory sf = conf.buildSessionFactory();
Session session = sf.openSession();
return session;
}
}