一、开篇

  下载Habernate所需要的jar包和mysql驱动。

  搭建简单的Habernate环境(一)_mysql

二、建立java项目并且导入所需要的包

  搭建简单的Habernate环境(一)_xml_02

三、建立实体类和配置映射文件

  user实体类


package testPackage;

public class user {
public String id;
public String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


  user配置文件


<?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="testPackage.user" table="user">
<id name="id">
<generator class="uuid"></generator>
</id>
<property name="name"/>
</class>
</hibernate-mapping>


  habernate.cfg.cml配置


<?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>
<!-- 数据库连接设置 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://120.78.155.**:3306/jwttoken</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping resource="testPackage/user.xml"/>
</session-factory>
</hibernate-configuration>


四、测试


package testPackage;



import java.util.UUID;

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

public class demo {

public static void main(String[] args)
{
user d=new user();
d.id=UUID.randomUUID().toString().replaceAll("-", "");
d.name="dirk";
Configuration configure = new Configuration().configure();

SessionFactory factory = configure.buildSessionFactory();
Session session = factory.openSession();
Transaction transaction= session.beginTransaction();
session.save(d);
transaction.commit();
System.out.print("ok");

}
}


 五、结果

  搭建简单的Habernate环境(一)_xml_03

六、遇到的问题

  搭建简单的Habernate环境(一)_mysql_04

  搭建简单的Habernate环境(一)_mysql_05