建表語句如下:
drop table student;
create table student(
stu_id integer not null primary key,
stu_username varchar2(20) not null,
stu_password varchar2(20) not null);
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>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="model/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
model.Student.java:
package model;
public class Student {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
O-R Mapping: model.Student.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="model">
<class name="Student" table="student">
<id name="id" column="stu_id" type="integer">
<generator class="native"/>
</id>
<property name="username" column="stu_username" type="string"></property>
<property name="password" column="stu_password" type="string"></property>
</class>
</hibernate-mapping>
測試:Test.java:
import model.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
Student s = new Student();
s.setId(1);
s.setUsername("admin");
s.setPassword("admin");
Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
Transaction t = session.beginTransaction();
session.save(s);
t.commit();
session.close();
}
}
階層如所示:(當然需要hibernate類庫的支援~Oracle驅動是在網上下的ojdbc5.jar)