hibernate学习笔记1_HelloWorld

一、前言

      hibernate是当今java主流的三大框架之一,应用于持久层,是一个典型的O/R Mapping框架。作用是让程序员可以以面向对象的方式访问数据库,利于程序扩展。

 

二、准备

      学习环境:hibernate3.6+mysql+MyEclipse5.5+tomcat6.0,例外需要下载slf4j-1.6.1(hibernate用于输出日志的插件)

 

三、HelloWorld步骤

      1.建立java项目

      2.引入hibernate所需jar包

 核心hibernate3.jar,必须的hibernate3.6/lib/required下所有、jpa下的hibernate-jpa-2.0-api-1.0.0.Final.jar(java持久化API),以及slf4j-1.6.1/slf4j-nop-1.6.1.jar

 

      3.建立数据库hibernate,表Student以及实体类Student.java

 

package jzl.hibernate.model;

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

 

      4.在Student类同目录下建立映射文件Student.hbm.xml(hibernate文档参照)

 

<?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="jzl.hibernate.model">
	<class name="Student">
		<id name="id"></id>
		<property name="name"></property>
		<property name="age"></property>
	</class>
</hibernate-mapping>

 

      5.在项目src目录下建立hibernate.cfg.xml的配置文件,去掉多余的配置。(hibernate文档参照)

 <?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">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <!-- <property name="connection.pool_size">1</property> -->

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</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><!-- 输出SQL语句 -->

        <!-- Drop and re-create the database schema on startup -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
        
	<!-- 使用Student.hbm.xml配置的方式指定实体类和表的关联关系 -->
        <mapping resource="jzl/hibernate/model/Student.hbm.xml"/>
        <!--<mapping class="jzl.hibernate.model.Teacher"/>--><!-- Annotation指定关联 -->
    </session-factory>
</hibernate-configuration>

      6.写测试类StudentTest

 

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import jzl.hibernate.model.Student;

public class StudentTest {
	
	public static void main(String[] args) {
		Student s = new Student();
		s.setId(1);
		s.setName("jzl");
		s.setAge(23);
		//hibernate操作数据库
		Configuration cfg = new Configuration();
		SessionFactory sf = cfg.configure().buildSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(s);
		session.getTransaction().commit();
		session.close();
		sf.close();
	}
}

 

      7.运行StudentTest,日志如下:

Hibernate: insert into Student (name, age, id) values (?, ?, ?)

 

四、HelloWorld优化,使用Annotation关联,建立辅助类。

      1.建立表Teacher和实体类Teacher。使用Annotation标记Teacher,则不需要在建立一个Teacher的映射文件关联数据表了。

 

package jzl.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.Id;
//@之后的就是Annotation类,Entity指明Teacher类为实体类,即与表Teacher相关联的类。@Id则指明主键
@Entity
public class Teacher {
	private int id;
	private String name;
	private String title;
	@Id
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
}

      2.放开以上hibernate.cfg.xml的<mapping class="jzl.hibernate.model.Teacher"/>配置。

      3.建立辅助类,使用单例创建SessionFactory。

package jzl.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

      4.建立测试类TeacherTest

    import org.hibernate.Session;

import org.hibernate.SessionFactory;

import jzl.hibernate.model.Teacher;
import jzl.hibernate.util.HibernateUtil;

public class TeacherTest {
	
	public static void main(String[] args) {
		Teacher s = new Teacher();
		s.setId(1);
		s.setName("jzl");
		s.setTitle("高级");

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(s);
		session.getTransaction().commit();
		session.close();
		sf.close();
	}
}

      7.运行StudentTest,日志如下:

         Hibernate: insert into Teacher (name, title, id) values (?, ?, ?)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值