create table employee(id Number(10),name varchar2(20))
<Hibernate-configuration>
<session-factory>
<property name="connection.username">用户名</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:数据库名</property>
<property name="connection.password">密码</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="dialect">org.Hibernate.dialect.OracleDialect</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</Hibernate-configuration>
<Hibernate-mapping>
<class name="src.employee" table="employee">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="name" column="name"/>
</class>
</Hibernate-mapping>
<generator class="increment"/>
可以实现id自动增加,也就是说,如果往数据库中插入一个name,那么id就自动加1。
<class name="src.employee" table="employee">
就是先指定了类对应的表。文件中的语句就是指定表中的字段与类中的属性的对应关系。
package src;
public class Employee{
private int id;
private String name;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
再看一下Test类:
package src;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class Test{
try{
SessionFactory sessionfactory = new Configuration().configure().BuildSessionFactory();
Session session = sessionfactory.opensession();
Transaction transaction = session.beginTransaction();
for(int i = 0;i<3;i++){
Employee employee = new Employee();
employee.setName("begin go "+i);
session.save(employee);
}
transcation.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
}
SessionFactory sessionfactory = new Configuration().configure().BuildSessionFactory();
得到configuration的实例。然后通过configure()读取mapping对应的hbm.xml文件的信息。