Java笔记8:Hibernate连接Oracle



1下载hibernate-3.6.0 Final.zip到任意目录,解压缩后得到hibernate目录

 

2下载slf4j-1.7.13.zip到任意目录,解压缩后得到slf4j-1.7.13

 

3操作数据库

sqlplus system/oracle

创建表

create table Student

(
 Student_ID  number(6) NOT NULLPRIMARY KEY,
 Student_Name varchar2(10) NOT NULL,
 Student_Age number(2) NOT NULL
);

创建序列号用于给表StudentStudent_ID赋值

CREATE SEQUENCEstudent_sequence 
INCREMENT BY 1
START WITH 1000
NOMAXVALUE
NOCYCLE
CACHE 10;

 

4新建一个名为Hiber的工程

 

5添加包

添加hibernate\jar中的所有包

Java笔记8:Hibernate连接Oracle_第1张图片 


添加slf4j-1.7.13中的slf4j-nop-1.7.13.jar

Java笔记8:Hibernate连接Oracle_第2张图片 


添加oraclejdbc驱动程序ojdbc6.jar

Java笔记8:Hibernate连接Oracle_第3张图片 


添加完成后

Java笔记8:Hibernate连接Oracle_第4张图片


6 添加两个配置文件和两个类

1hibernate.cfg.xml




    
    true
    
    org.hibernate.dialect.OracleDialect
    
    
    
        oracle.jdbc.driver.OracleDriver
    
    
    
        jdbc:oracle:thin:@localhost:1521:orcl
    
    
    system
    
    oracle
    



2Student.java

public class Student
{
    private int student_id;
    private String student_name;
    private int student_age;

    public int getStudent_id()
    {
        return student_id;
    }
    public String getStudent_name()
    {
        return student_name;
    }
    public int getStudent_age()
    {
        return student_age;
    }
    public void setStudent_id(int id)
    {
        this.student_id = id;
    }
    public void setStudent_name(String name)
    {
        this.student_name = name;
    }
    public void setStudent_age(int age)
    {
        this.student_age = age;
    }
}

3Student.hbm.xml




    
        
            
                student_sequence
            
        
        
        
    
 

4Test.java

importorg.hibernate.*;
import org.hibernate.cfg.*;

public class Test
{
    public static voidmain(String[]args)
    {
        try
        {
            //通过Configuration获得一个SessionFactory对象
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
            //打开一个Session
            Session session= sf.openSession();
            //开始一个事务
            Transaction tx =session.beginTransaction();
            //创建一个Student对象
            Student stu =new Student();
            //通过Student的setter方法改变它的属性
            //注意student_id不用我们设置
            stu.setStudent_name("zhangsan");
            stu.setStudent_age(18);
            //通过session的save()方法将Student对象保存到数据库中
            session.save(stu);
            //提交事务
            tx.commit();
            //关闭会话
            session.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
 

验证

1)运行Test.java,结果为

Hibernate: select student_sequence.nextvalfrom dual

Hibernate: insert into Student(Student_Name, Student_Age, student_id) values (?, ?, ?)

 

2)从Oracle数据库中查询

Java笔记8:Hibernate连接Oracle_第5张图片

你可能感兴趣的:(Java)