Posted on 2006-11-05 20:38
苑 阅读(162)
评论(0) 编辑 收藏 所属分类:
Hibernate持久层框架学习
首先打开mySQL数据新建一个数据库HibernateTest
create database HibernateTest;
use HibernateTest;
CREATE TABLE USER (
user_id CHAR(32) NOT NULL PRIMARY KEY,
name VARCHAR(16) NOT NULL,
sex CHAR(1),
age INT
);
然后编写一个User.java文件
public class User {
private String id;
private String name;
private char sex;
private int age;
public int getAge() {
return age;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public char getSex() {
return sex;
}
public void setAge(int i) {
age = i;
}
public void setId(String string) {
id = string;
}
public void setName(String string) {
name = string;
}
public void setSex(char c) {
sex = c;
}
}
User.hbm.xml文件是用来描述数据库中表的字段信息的配置文件内容如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="onlyfun.caterpillar.User" table="USER">
<id name="id" type="string" unsaved-value="null">
<column name="user_id" sql-type="char(32)" />
<generator class="uuid.hex"/>
</id>
<property name="name" type="string" not-null="true">
<column name="name" length="16" not-null="true"/>
</property>
<property name="sex" type="char"/>
<property name="age" type="int"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml文件时用来连接数据库时使用的配置文件
<?xml version='1.0' encoding='big5'?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/HibernateTest</property>
<property name="connection.username">caterpillar</property>
<property name="connection.password">123456</property>
<mapping resource="User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
然后我们编写一个测试类来测试一下刚才的配置
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
public class HibernateTest {
public static void main(String[] args) throws HibernateException {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
User user = new User();
user.setName("caterpillar");
user.setSex('M');
user.setAge(28);
Session session = sessionFactory.openSession();
Transaction tx= session.beginTransaction();
session.save(user);
tx.commit();
session.close();
sessionFactory.close();
System.out.println("新增資料OK!請先用MySQL觀看結果!");
}
}