Hibernate学习笔记(一)

现在我们来学习Hibernate,我用的是Hibernate4.1.3,首先我们应该知道Hibernate是什么?

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSPWeb应用中使用,最具革命意义的是,Hibernate可以在应用EJBJ2EE架构中取代CMP,完成数据持久化的重任。(百度百科)

下面让我们来看一个图形:

它清楚的表明了Hibernate的运行过程。它在数据库层面上进行了封装,让我们可以用面向对象的思维了和数据库打交道了,下面我们来实现这个过程。

1.建立xml版本的HelloWorld

首先我定义了一个Student类,代码如下:

public class Student {
	private String name;
	private int id;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

然后在MySQL中建立了一张表student,建表语句如下:

create database hibernate;
 use hibernate;
 create table student(id int primary key, name varchar(20) , age int);

下面我们要配置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>      
        <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>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</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>
        <property name="format_sql">true</property>    
		  <mapping resource="csy/model/Student.hbm.xml"/>	
    </session-factory>

</hibernate-configuration>

可以清楚的看到在这个文件中已经对连接数据库进行了配置,免去了我们手动连接的麻烦,然后有一个dialect,文档中对它有这样的介绍:

The first line of portability for Hibernate is the dialect, which is a specialization of the org.hibernate.dialect.Dialect contract. A dialect encapsulates all the differences in how Hibernate must communicate with a particular database to accomplish some task like getting a sequence value or structuring a SELECT query. Hibernate bundles a wide range of dialects for many of the most popular databases. If you find that your particular database is not among them, it is not terribly difficult to write your own.

大致意思是一种方言封装了Hibernate必须和database进行交互来完成一些工作(例如获得一个序列值或者一个select语句的结构化的)所有不同的方法,Hibernate为许多最流行的数据库捆绑了一个广泛的方言。

因为我们用的数据库是MySQL所以org.hibernate.dialect.MySQLDialect

show_sql意思是是否展现sql语句,到这为止我们还只是对数据库连接和一些交互进行了配置,从上面的图上我们可以看到,实体类也就是Student类也必须和database建立连接,所以 <mapping resource="csy/model/Student.hbm.xml"/>表示映射资源来自Student.hbm.xml,如下:

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

首先应该注意的是这个文件最好也在Model层下面,这样就和前面讲到的命名规则一致了,class表示实体类对应的表的名字,如果是一样的则table可以不写,id表示主键对应的表中的,一样也可以不写,property 表示属性对应表中的字段名。下面我们来些一个测试类:

public class StudentTest {
	public static void main(String[]args){
		Student s = new Student();
		s.setId(1);
		s.setName("s1");
		s.setAge(1);
		
		Configuration cfg = new Configuration();
		cfg.configure();
		ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); 
		SessionFactory sf = cfg.buildSessionFactory(sr); 

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

因为我用的是4.1.3,它的buildSessionFactory()方法已经废弃,这个要注意。同时和数据库进行交互要注意在出现异常时的回滚,所以在save方法前后要加上beginTransaction()getTransaction().commit()

2.建立Annotation版本的HelloWorld

1、 创建teacher表,create table teacher(id int primary key,name varchar(20),title varchar(10));

2、 创建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;
	}
	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;
	}
}

注意加入相应的annotation的jar包

参考Annotation文档建立对应的注解

import javax.persistence.Entity;
import javax.persistence.Id;
/** @Entity 表示下面的这个Teacher是一个实体类
 * @Id 表示主键Id*/
@Entity	//***
public class Teacher {
	private int id;	
	private String name;	
	private String title;
	//设置主键使用@Id
	@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;
	}}

 hibernate.cfg.xml中建立映射<maping class="csy.model.Teacher"/>

测试文档和上面查不多但要注意new 的是一个AnnotationConfiguration.






 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值