今天忙了一整天,终于搭建好了我的第一个Hibernate程序,中间关于hibernate.cfg.xml的问题搞了半天,不过最后还是搞明白了,下面来讲一讲过程。

  首先在你的eclipse中安装Hibernate Tools插件方便创建cfg.cml与hbm.xml文件。然后创建配置hibernate.cfg.xml文件:

奥添加yi

当然在最前面还要添加hibernate jar包,musql driver等,由于我使用maven管理项目,因此直接在maven的pom文件中添加就可以了。

在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 name="HibernateSessionFactory">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 在控制台输出SQL语句 -->
<property name="show_sql">true</property>
<!-- Hibernate启动时自动创建表结构 -->
<property name="hbm2ddl.auto">create</property>
<!-- 不加 可能出现异常 -->
<property name="current_sesson_context_class">thread</property>
<!-- 指定Cat类为Hibernate实体类 -->
<mapping resource="config/Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>

第九行url后面的 hibernate?characterEncoding=utf-8 是hibernate要操作的数据库名称,需要你自己先创建:

create database hibernate character set 'utf8'

19行Cat类是需要你自己创建的POJO实体类,实体类(Entity)是指与数据库有映射关系的Java类使用@Entity后Cat就被申明为了一个实体类。实体类还需配置对应的表名(@Table),主键(@Id),普通属性(@Column)对应列名等。

 package com.lxiao.model;

 import java.util.Date;

 import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType; @Entity
@Table(name="tb_cat")
public class Cat { @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer Id; @Column(name = "name")
private String name; @Column(name = "description")
private String description; @Column(name = "age")
private Integer age; @Column(name="sex")
private String sex; @ManyToOne
@JoinColumn(name = "mother_id")
private Cat mother; @Temporal(TemporalType.TIMESTAMP)
@Column(name = "createDate")
private Date createDate; public Integer getId() {
return Id;
} public void setId(Integer id) {
Id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public Cat getMother() {
return mother;
} public void setMother(Cat mother) {
this.mother = mother;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
} }

值得一提的是,该POJO类在定义玩le私有变量后,可以用eclipse自动生成getter,setter方法,免去了手写的枯燥。

然后创建Cat.hbm.xml文件,添加你的POJO类,我这里就是Cat,使用Hibernate tools工具创建时选择添加类,

然后一路next就可以了,最后就在hibernte.cfg.xml中就可以配置实体类了,用<mapping resource="config/Cat.hbm.xml">,这是针对xml文件配置,如果是@注解配置,使用<maping class="com.lxiao.model.Cat">

然后我们写一个HibernateUtil类来加载config文件hibernate.cfg.xml:

 package com.lxiao.hibernate;

 import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateUtil {
private static final SessionFactory factory; static{
try{
factory = new Configuration().configure("config/hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable e){
System.out.println("Initial sesionFactory failed..."+e);
throw new ExceptionInInitializerError(e);
}
} public static SessionFactory getSessionFactory(){
return factory;
}
}

加载xml配置的实体类要使用Configuration加载Hibernate配置。

最后我们要使用一下Cat类,让Hibernate自动为我们创建表,执行相应数据库操作。这整个流程是:Hibernate保存数据是,先通过sesonFactory开启一个session会话(作用相当于JDBC中的Connection),然后开启一个事务(Transaction),然后保存代码,提交事务,关闭session。其它数据库操作也是类似的。下面是我的程序:

 package com.lxiao.hibernate;

 import java.awt.Font;
import java.util.Date;
import java.util.List; import javax.swing.JOptionPane; import org.hibernate.Session;
import org.hibernate.Transaction; import com.lxiao.model.Cat; public class CatTest {
public static void main(String[] args){
Cat motherCat = new Cat();
motherCat.setName("Mary White");
motherCat.setDescription("The mama cat...");
motherCat.setCreateDate(new Date()); Cat kitty = new Cat();
kitty.setMother(motherCat);
kitty.setName("Kitty");
kitty.setDescription("Hello Kitty");
kitty.setCreateDate(new Date()); Cat mimmy = new Cat();
mimmy.setMother(motherCat);
mimmy.setName("Mimmy");
mimmy.setDescription("Kitty's little twn sister");
mimmy.setCreateDate(new Date()); Session session = HibernateUtil.getSessionFactory().openSession();//开启一个Hibernate对话
Transaction transaction = session.beginTransaction(); session.persist(motherCat);//将mother保存进数据库
session.persist(kitty);
session.persist(mimmy); List<Cat> catlist = session.createQuery(" from Cat ").list(); StringBuffer resultBuffer = new StringBuffer();
resultBuffer.append("All cat in db: \r\n\r\n"); for(Cat cat : catlist){
resultBuffer.append("Cat: "+cat.getName()+", ");
resultBuffer.append("Mothercat: "+(cat.getMother() == null ? "no record" : cat.getMother().getName()));
resultBuffer.append("\r\n");
}
transaction.commit();//提交事务
session.close();//关闭数据库 JOptionPane.getRootFrame().setFont(new Font("Arial",Font.BOLD,14));
JOptionPane.showMessageDialog(null, resultBuffer.toString()); }
}

运行结果:

我在数据库的查询结果如下:

在hibernate.cfg.xml配置文件中,我们有:

 <!-- Hibernate启动时自动创建表结构 -->
15 <property name="hbm2ddl.auto">create</property>

每次Hibernate会先删掉表然后再创建表。

最后放上我的项目目录结构:

总之我的第一个Hibernate程序总算是可以运行了,也了解了不少Hiernate这个ORM框架的东西,它给开发中关于数据库操作带来了很多便利,很值得学习,了解。

--程序员的道路漫漫,继续努力。。。

参考书籍:Java Web开发王者归来,刘京华编著。

最新文章

  1. css之IE透明度
  2. dereverberation
  3. 论文阅读(Weilin Huang——【AAAI2016】Reading Scene Text in Deep Convolutional Sequences)
  4. uMlet建模工具
  5. Ignatius&#39;s puzzle
  6. 【Android 界面效果42】如何自定义字体
  7. ResolverService跨子网的广播问题
  8. Insert data from excel to database
  9. pagination jquery最简单的分页【无刷新和刷新都通用】
  10. codeforces 455C 并查集
  11. 《SAS编程和数据挖掘商业案例》第14部分学习笔记
  12. Chapter 2 Open Book——28
  13. js 弹出 隐藏层和cookie
  14. 【Xilinx-Petalinux学习】-02-建立PetaLinux工程
  15. node-sass下载失败 关于webpack
  16. Go-day04
  17. [日常工作]Win2008r2 以及更高版本的操作系统安装Oracle10.2.0.5
  18. 两道SQL题目
  19. Hive安装与配置--- 基于MySQL元数据
  20. odoo tree视图 当页不弹窗显示方法

热门文章

  1. Dijkstra算法构造单源点最短路径
  2. Jackson中的那些坑
  3. Lesson: Introduction to JAXP
  4. 基于RMAN从活动数据库异机克隆(rman duplicate from active DB)
  5. Java通过代理server上网
  6. 关于Parse库的配置问题
  7. windows 下一个 easy_install 设备
  8. NVMe 图解
  9. PureMVC(JS版)源码解析(十):Controller类
  10. 使用CSS的类名交集复合选择器