(1)第一个程序(使用配置文件和注解)

使用配置文件建立Hibernate程序


0. Jar包


1. 建立实体类Student 

public class Student {

	private int id;
	private String name;
	private int age;
}

2. 建立数据库表student

id(key),name,age三列


3. 建立映射文件 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.vin.hibernate.model">
	<class name="Student" table="student">
		<id name="id" column="id"></id>
		<property name="name" column="name"></property>
		<property name="age" column="age"></property>
	</class>
</hibernate-mapping>
实体类与表的对应:<class>标签中,name=实体类名,table=表名

实体类属性与表字段的对应:<property>标签中,name=实体类属性,column=表字段。<id>是主键字段的<property>


4. 建立Hibernate配置文件hibernate.cfg.xml 

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

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

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</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/vin/hibernate/model/Student.hbm.xml"/>
        <!-- <mapping class="com.vin.hibernate.model.Teacher"/> -->

    </session-factory>

</hibernate-configuration>
从文档copy,更改自己的jdbc配置即可。

5. 辅助类,生产sessionFactory

package com.vin.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) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

6. 测试

public class Test {

	@Test
	public void save(Student s) {
		
		SessionFactory sf =  HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		
		session.beginTransaction();
		
		session.save(s);
		System.out.println(s);
		
		session.getTransaction().commit();
		session.close();
		sf.close();
	}
	
}
</pre><p></p><p><span style="font-size:18px;"><span style="font-size: 14px;">7. 测试结果</span></span></p><p><pre name="code" class="java">Student [id=3, name=dominique, age=13]
Hibernate: insert into student (name, age, id) values (?, ?, ?)


使用Annotation建立Hibernate程序

0. 加入annotation的jar包



1. 建立实体类Teacher

</pre><p><span style="font-size:14px"></span><pre name="code" class="java">@Entity
@Table(name="teacher")
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;
	}
	@Column(name="name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name="title")
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	@Override
	public String toString() {
		return "Teacher [id=" + id + ", name=" + name + ", title=" + title
				+ "]";
	}
		
}


2. 建立数据库表student

id(key),name,age三列

3. 无需建立映射文件。而在实体类Teacher上注解

@Entity表明javabean的实体,

@Table表明实体类对应DB内的表名,如果不屑@Table,则默认与实体类名相同的表名

@Column表明属性对应DB表内的字段,如果不写@Column,则默认与属性名相同的字段

主键上注解@Id

4. 建立Hibernate配置文件hibernate.cfg.xml 

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

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

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</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 class="com.vin.hibernate.model.Teacher"/>

    </session-factory>

</hibernate-configuration>
从文档copy,更改自己的jdbc配置即可。
<mapping>中,改为class

5. 辅助类,生产sessionFactory

package com.vin.hibernate.util;


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


public class HibernateAnnotationUtil {


    private static final SessionFactory sessionFactory = buildSessionFactory();


    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }


    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

使用Annotation时,不再是new Configuratino, 而是new AnnotationConfiguration。


6. 测试

public class Test {

	@Test
	public void save(Teacher t) {
		
		SessionFactory sf =  HibernateAnnotationUtil.getSessionFactory();
		Session session = sf.openSession();
		
		session.beginTransaction();
		
		session.save(t);
		System.out.println(t);
		
		session.getTransaction().commit();
		session.close();
		sf.close();
	}
	
}

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值