Hibernate入门心得(一)

2014-11-24 08:39:22 · 作者: · 浏览: 0

开发阶段:

新建一个JAVA项目,目录结构如下:

将准备的jar包引入到项目中。

hibernate.cfg.xml:(Hibernate的配置文件,放在项目的src目录下):< xml version='1.0' encoding='UTF-8' >

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">






com.mysql.jdbc.Driver

20

jdbc:mysql://localhost:3306/book

username

passwrod

org.hibernate.dialect.MySQL5Dialect

true

true
thread





这里配置的是MySQL数据库的驱动和连接,在开始的时候忘了加26行,结果调试的时候出错,得不到session,关于这个标签的使用,请参考如下文章:http://blog.sina.com.cn/s/blog_5ecfe46a0100e467.html 第28行是对象关系映射文件的配置.

Person.java:(人的实体类,对应到关系数据库中的blog表)package com.sunflower.bean;


import java.io.Serializable;

/**
* 博客用户的实体类
*
* @author hanyuan
* @time 2012-7-8 下午11:53:23
*/
public class Person implements Serializable {
private Integer id;
private String username;
private String password;
private String caption;
private String content;

public Integer getId() {
return id;
}

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

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getCaption() {
return caption;
}

public void setCaption(String caption) {
this.caption = caption;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

}
第12~16行中的属性对应到数据库中的blog表的字段,其中id是主键索引.

Person.hbm.xml:(对象关系映射配置文件)< xml version="1.0" >

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">





























表示对象对应的表,字段是必须要有的,表示主键。开始的时候没有加第13行,结果调试出错,需要加上标签,这里设置为自增类型.关于标签的使用,这个配置文件的是以hbm.xml结尾的,名字建议命名为对象名.hbm.xml,并且和实体类对象放在同一个包下,这样比较好找.

Test.java:(调用Hibernate API 插入数据)package com.sunflower.main;


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

import com.sunflower.bean.Person;

public class Test {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
// 读取Hibernate的配置信息
Configuration config = new Configuration();
config.configure();

// 读取配置里面的SessionFactory
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();

Person person = new Person();
person.setUsername("邓光桥");
person.setPassword("123");
person.setCaption("Hibernate");
person.setContent("Hibernate 入门实例");

// 提交事务
session.save(person);
transacti