相关基础概念请从其它教材简单了解,这里仅记录下第一个Hibernate程序的实现步骤。

环境说明:

java开发工具:eclipse MARS.2 Release(4.5.2)

hibernate版本:hibernate-release-4.3.6.Final

Web 容器:Tomcat v8.0

数据库:MySQL 5.6.19-enterprise-commercial-advanced

jdbc驱动:mysql-connector-java-commercial-5.1.30-bin.jar

1.下载hibernate。

2.下载jdbc驱动文件。

3.在eclipse中新建web project,命名为firsthibernate。

4.拷贝hibernate/lib/required文件夹下的所有jar文件、以及jdbc驱动文件(此文件另外下载)到项目的WEB-INF/lib文件夹下,拷贝hibernate/project/etc下的hibernate.cfg.xml文件到项目的src目录下。

5.新建实体类Cat,Hibernate中配置实体类有两种方法:XML文件配置和@注解配置,本例采用@注解配置,相关注解代表的含义在代码中都有注明如下:

package com.levice.firsthibernate.bean;

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 //注解Entity表示该类能被Hibernate持久化
@Table(name = "tb_cat") //指定该Entity对应的数据表名
public class Cat { @Id //指定该列为主键。主键类型最好不要使用int等原始类型
@GeneratedValue(strategy = GenerationType.AUTO) //主键类型auto表示该主键为自增长型
private Integer id; @Column(name = "name") //指定该属性对应的数据库表的列为name,列名与属性名一样时这句注解可省略
private String name; @Column(name = "description")
private String description; @ManyToOne //指定实体类之间的关系,本例表示多对一关系
@JoinColumn(name = "mother_id")
private Cat mother; @Temporal(TemporalType.TIMESTAMP)//日期类型(DATE,TIME或TIMESTEMP)
@Column(name = "birthday")
private Date birthday; //getters and setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.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 Cat getMother() {
return mother;
}
public void setMother(Cat mother) {
this.mother = mother;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

6.修改配置文件hibernate.cfg.xml,内容及注释如下:

<!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>
<!-- 配置JDBC -->
<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">123456</property> <!-- 指定使用MySQL数据库格式的SQL语句 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 指定在控制台打印生成的SQL语句 -->
<property name="show_sql">true</property> <!-- 指定Hibernate启动时自动创建表结构 -->
<property name="hbm2ddl.auto">create</property> <!-- 加上这一句以防止未知错误 -->
<property name="current_session_context_class">thread</property> <!-- 指定Cat类为Hibernate实体类 -->
<mapping class="com.levice.firsthibernate.bean.Cat"/>
</session-factory>
</hibernate-configuration>

7.初始化数据库,在MySQL中创建数据库hibernate,SQL代码如下:

create database hibernate;

8.配置HibernateUtil,就是修改HibernateUtil.java文件,这个文件在下载的hibernate文件中有,但我Copy过来的时候,一直没调试成功,于是采用了一个版本比较老的HibernateUtil。这个文件的作用是获取SessionFactory从而获取Session,不同版本的hiberate中获取SessionFactory的方法都不同,这里可以新建一个HibernateUtil.java文件,然后把下面的代码copy进去。

package com.levice.firsthibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; @SuppressWarnings("deprecation")
public class HibernateUtil { private static final SessionFactory sessionFactory;
static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable ex){
System.err.println("Initial SessionFactory creation failed.");
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}

9.执行Hibernate程序,创建一个包含主函数main的类CatTest,代码及注释如下:

package com.levice.firsthibernate.test;

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.levice.firsthibernate.bean.Cat;
import com.levice.firsthibernate.util.HibernateUtil; public class CatTest { public static void main(String[] args) {
// TODO Auto-generated method stub /*初始化几只Cat的信息*/
Cat mother = new Cat();
mother.setName("Mother White");
mother.setDescription("This is mother cat");
mother.setBirthday(new Date()); Cat kitty = new Cat();
kitty.setMother(mother);
kitty.setName("Kitty");
kitty.setDescription("This is Kitty");
kitty.setBirthday(new Date()); Cat tom = new Cat();
tom.setMother(mother);
tom.setName("Tom");
tom.setDescription("This is Tom");
tom.setBirthday(new Date()); @SuppressWarnings("static-access")
Session session = new HibernateUtil().getSessionFactory().openSession(); //获取session并open,开启一个Hibernate会话
Transaction trans = session.beginTransaction(); //开启一个事务 session.persist(mother); //将mother保存到数据库
session.persist(kitty);
session.persist(tom); @SuppressWarnings("all")
List<Cat> catList = session.createQuery(" from Cat ").list(); //查询数据库中所有的猫
StringBuffer result = new StringBuffer();
result.append("all cats: \r\n\r\n");
for (Cat cc : catList) {
result.append("name:" + cc.getName() + "\n");
result.append("mother:" + (cc.getMother() == null ? "null" : cc.getMother().getName()) + "\n");
result.append("description:" + cc.getDescription() + "\r\n\r\n");
} trans.commit(); //提交事务
session.close(); //关闭Hibernate会话 //用Swing显示查询结果
JOptionPane.getRootFrame().setFont(new Font("Arial", Font.BOLD, 14));
JOptionPane.showMessageDialog(null, result.toString()); } }

10.运行CatTest,可以看到如下输出:

控制台输出的SQL语句如下:

Hibernate: alter table tb_cat drop foreign key FK_dix3h50rxo8ahrcu5roir75n1
Hibernate: drop table if exists tb_cat
Hibernate: create table tb_cat (id integer not null auto_increment, birthday datetime, description varchar(255), name varchar(255), mother_id integer, primary key (id))
Hibernate: alter table tb_cat add constraint FK_dix3h50rxo8ahrcu5roir75n1 foreign key (mother_id) references tb_cat (id)
Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: select cat0_.id as id1_0_, cat0_.birthday as birthday2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother_i5_0_, cat0_.name as name4_0_ from tb_cat cat0_

Hibernate入门笔记的更多相关文章

  1. Java ORM Hibernate 入门笔记

    一.下载 官网地址:http://hibernate.org/ Hibernate下有ORM(关系型数据库).OGM(NoSQL数据库).Search(对象全文检索).Validator的工具. OR ...

  2. Hibernate学习笔记(一)

    2016/4/18 19:58:58 Hibernate学习笔记(一) 1.Hibernate框架的概述: 就是一个持久层的ORM框架. ORM:对象关系映射.将Java中实体对象与关系型数据库中表建 ...

  3. Hibernate 学习笔记一

    Hibernate 学习笔记一 今天学习了hibernate的一点入门知识,主要是配置domain对象和表的关系映射,hibernate的一些常用的配置,以及对应的一个向数据库插入数据的小例子.期间碰 ...

  4. 三大框架之hibernate入门

    hibernate入门   1.orm      hibernate是一个经典的开源的orm[数据访问中间件]框架           ORM( Object Relation Mapping)对象关 ...

  5. 每天成长一点---WEB前端学习入门笔记

    WEB前端学习入门笔记 从今天开始,本人就要学习WEB前端了. 经过老师的建议,说到他每天都会记录下来新的知识点,每天都是在围绕着这些问题来度过,很有必要每天抽出半个小时来写一个知识总结,及时对一天工 ...

  6. ES6入门笔记

    ES6入门笔记 02 Let&Const.md 增加了块级作用域. 常量 避免了变量提升 03 变量的解构赋值.md var [a, b, c] = [1, 2, 3]; var [[a,d] ...

  7. [Java入门笔记] 面向对象编程基础(二):方法详解

    什么是方法? 简介 在上一篇的blog中,我们知道了方法是类中的一个组成部分,是类或对象的行为特征的抽象. 无论是从语法和功能上来看,方法都有点类似与函数.但是,方法与传统的函数还是有着不同之处: 在 ...

  8. Hibernate入门案例及增删改查

    一.Hibernate入门案例剖析: ①创建实体类Student 并重写toString方法 public class Student { private Integer sid; private I ...

  9. React.js入门笔记

    # React.js入门笔记 核心提示 这是本人学习react.js的第一篇入门笔记,估计也会是该系列涵盖内容最多的笔记,主要内容来自英文官方文档的快速上手部分和阮一峰博客教程.当然,还有我自己尝试的 ...

随机推荐

  1. Composer概述及其自动加载探秘

    composer概述 一开始,最吸引我的当属 Composer 了,因为之前从没用过 Composer . Composer 是PHP中用来管理依赖关系的工具,你只需在自己的项目中声明所依赖的外部工具 ...

  2. Kafka 文档引言

    原文地址:https://kafka.apache.org/documentation.html#semantics 1.开始 1.1 引言 Kafka是一个分布式,分区队列,冗余备份的消息存储服务. ...

  3. SQL Server-简单查询示例(十一)

    前言 本节我们讲讲一些简单查询语句示例以及需要注意的地方,简短的内容,深入的理解,Always to review the basics. EOMONTH 在SQL Server 2012的教程示例中 ...

  4. 使用swagger作为restful api的doc文档生成

    初衷 记得以前写接口,写完后会整理一份API接口文档,而文档的格式如果没有具体要求的话,最终展示的文档则完全决定于开发者的心情.也许多点,也许少点.甚至,接口总是需要适应新需求的,修改了,增加了,这份 ...

  5. 执行插入语句,object val = cmd.ExecuteScalar() val = null

    在写接口的过程中遇到错误:空对象不能转换为值类型 因为我们使用的是petapoco,经过调试后发现是 object val = cmd.ExecuteScalar() 这一句造成的报错, val = ...

  6. 基于CkEditor实现.net在线开发之路(7)列表页面开发动作介绍

    一个列表页面不止是查询,它也包含了很多业务上功能的实现,这些业务功能的实现的逻辑我称之为动作.如触发单击按钮删除数据,更改业务表数据,调用webService,调用WCF接口,弹出新窗体新增.修改.查 ...

  7. 工业物联网或系统集成中应用消息队列(ActiveMQ,C#的demo)的场景全面分析

    1.[连载]<C#通讯(串口和网络)框架的设计与实现> 2.[开源]C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 2.应用SuperIO(SIO)和开源跨平台物联网框 ...

  8. IIS初始化(预加载),解决第一次访问慢,程序池被回收问题

    你以为你可以慢,那是不可能的!你以为你可以不动,那也是不可能的! 河南是守株待兔故事情节的发源地,讲的是懒惰的农夫坐在树桩旁等待可爱的小毛兔撞树的故事,那么这种事情怎么可能天天出现呢!你以为的事并一定 ...

  9. iOS 升级HTTPS通过ATS你所要知道的

    由于苹果规定2017年1月1日以后,所有APP都要使用HTTPS进行网络请求,否则无法上架,因此研究了一下在iOS中使用HTTPS请求的实现.网上搜索了一些比较有用资料,大家可以参考下 苹果强制升级的 ...

  10. 菜单(Menu)的三中创建方式——Android开发之路2

    菜单的三种创建方式 一.OptionsMenu---选项菜单 Android应用中的菜单默认是隐藏的,只有当用户点击手机上的MENU键,系统才会显示菜单.这种菜单叫做选项菜单(Options Menu ...