• Hibernate连接数据库


    今天开始学Hibernate了,按照先脉络后细节、先操作后原理的学习顺序,那么第一个要学习的就是Hibernate版的HelloWorld了,即如何连接并操作数据库。

    Hibernate是什么,Hibernate有什么作用,先撇开不谈,现在我们只知道Hibernate是对JDBC的进一步封装即可。

    一、第一个案例

    实验环境:Hibernate3.3.2+SQL Server 2005

    实验步骤:

    (1)、新建Java项目(Hibernate是一个非常独立的框架)

    (2)、引入相应的jar包

    a)Hibernate所需jar包

    • hibernate core
    •  /required
    • slf-nop jar

    b)SQL Server所需的JDBC驱动包

    (3)在SQL Server中建立对应的数据库以及表

    create database hibernate;
    use hibernate;
    create table Student (id int primary key, namevarchar(20), age int);
    

    (4)新建和配置Hibernate的配置文件hibernate.cfg.xm

    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    
        <session-factory>
    
            <!-- Database connection settings -->
            <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
            <property name="connection.url">jdbc:sqlserver://127.0.0.1:1433;DatabaseName=hibernate</property>
            <property name="connection.username">sa</property>
            <property name="connection.password">123456</property>
    
            <!-- JDBC connection pool (use the built-in) -->
            <!-- <property name="connection.pool_size">1</property> -->
    
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
    
            <!-- Enable Hibernate's automatic session context management -->
            <!-- <property name="current_session_context_class">thread</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="com/chongqing/hibernate/model/Student.hbm.xml"/>
    
        </session-factory>
    
    </hibernate-configuration>
    

    (5)建立Student 类

    package com.chongqing.hibernate.model;
    
    public class Student {
    	private int id;
    	private String name;
    	private int age;
    	
    	public int getId() {
    		return id;
    	}
    	public String getName() {
    		return name;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    
    }
    

    (6)建立Student 映射文件 Student.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping package="com.chongqing.hibernate.model">
    	<class name="Student">
    		<id name="id"></id>
    		<property name="name"></property>
    		<property name="age"></property>
    	</class>
    </hibernate-mapping>
    

    (7)写测试类Main,在Main中对Student对象进行直接的存储测试

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    import com.chongqing.hibernate.model.Student;
    
    public class StudentTest {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Student s = new Student();
    		
    		s.setId(1);
    		s.setName("s1");
    		s.setAge(1);
    		
    		//创建Configuration,该对象用于读取hibernate.cfg.xml配置文件,并完成初始化
    		Configuration cfg = new Configuration().configure();
    		
    		//创建SessionFactory,一个SessionFactory对应一个数据存储源
    		SessionFactory sf = cfg.buildSessionFactory();
    		
    		//创建session,相当于JDBC中的Connection,主要此处的session并不是web中的session,
    		Session session = sf.openSession();
    		
    		//Hibernate要求在进行增加,删除,修改的时候使用事务
    		session.beginTransaction();
    		
    		session.save(s);
    		
    		//提交
    		session.getTransaction().commit();
    		
    		session.close();
    		sf.close();
    
    	}
    
    }
    

    二、Annotation版本的HelloWorld

    使用Annotation可以不用配置映射文件Student.hbm.xml,直接在实体类上建立相关的注解:

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.cfg.Configuration;
    
    import com.chongqing.hibernate.model.Student;
    
    public class StudentTest {
    
    	public static void main(String[] args) {
    
    		Student s = new Student();
    		
    		s.setId(3);
    		s.setName("s3");
    		s.setAge(3);
    		
    		//注意这里要使用org.hibernate.cfg.AnnotationConfiguration来创建Configuration,才能使用Annotation功能
    		Configuration cfg = new AnnotationConfiguration();
    		SessionFactory sf = cfg.configure().buildSessionFactory();
    		Session session = sf.openSession();
    		session.beginTransaction();
    		session.save(s);
    		session.getTransaction().commit();
    		session.close();
    		sf.close();
    
    	}
    
    }
    

    需要在Hibernate lib中加入Annotation的jar包:

    • hibernate annotaion jar
    • ejb3 persistence jar
    • hibernate common-annotations.jar

     及在配置文件hibernate.cfg.xm建立映射为:

            <mapping class="com.chongqing.hibernate.model.Student"/>
    
  • 相关阅读:
    我的git笔记
    我的 Sublime Text 2 笔记
    在Windows系统配置Jekyll
    纯CSS3打造七巧板
    JavaScript原型之路
    基于Grunt构建一个JavaScript库
    How React Works (一)首次渲染
    hadoop2.4 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
    pyinstaller打包python源程序访问hive
    hadoop balance均衡datanode存储不起作用问题分析
  • 原文地址:https://www.cnblogs.com/yzy-blogs/p/6728415.html
Copyright © 2020-2023  润新知