Hibernate学习笔记


Hibernate是什么:






Hibernate 架构:






下载、安装、必要的 jar包、环境CLASSPAST的设置(此步骤省略)



Hibernate框架的使用步骤:
1、创建Hibernate的配置文件(hibernate.cfg.xml)
2、创建持久化类,即事实上例须要保存到数据库中的类(User.java)
3、创建对象-关系映射文件(User.hbm.xml)

4、通过Hibernate API编写訪问数据库的代码



配置文件 hibernate.cfg.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><!-- Assume testone is the database name --><property name="hibernate.connection.url">jdbc:mysql://localhost/testone</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">yanfei</property><property name="hibernate.show_sql">true</property><!-- List of XML mapping files --><mapping resource="resource/Employee.hbm.xml" /></session-factory>
</hibernate-configuration>




创建持久化类:

package com.jiangge.hblearn;/*** @author jiangge* */
public class Employee
{private int id;private String firstName;private String lastName;private int salary;public Employee(){}public Employee(String firstName, String lastName, int salary){super();this.firstName = firstName;this.lastName = lastName;this.salary = salary;}public int getId(){return id;}public void setId(int id){this.id = id;}public String getFirstName(){return firstName;}public void setFirstName(String firstName){this.firstName = firstName;}public String getLastName(){return lastName;}public void setLastName(String lastName){this.lastName = lastName;}public int getSalary(){return salary;}public void setSalary(int salary){this.salary = salary;}
}



创建数据库中的表:

create table EMPLOYEE (id INT NOT NULL auto_increment,first_name VARCHAR(20) default NULL,last_name  VARCHAR(20) default NULL,salary     INT  default NULL,PRIMARY KEY (id)
);


配置文件--映射文件Employee.hbm.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.jiangge.hblearn.Employee" table="EMPLOYEE"><meta attribute="class-description">This class contains the employee detail.</meta><id name="id" column="id" type="int"><generator class="native" /></id><property name="firstName" column="first_name" type="string" /><property name="lastName" column="last_name" type="string" /><property name="salary" column="salary" type="int" /></class>
</hibernate-mapping>



创建測试文件--CURD操作:

package com.jiangge.hblearn;import java.util.List;
import java.util.Iterator;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;/*** hibernate CRUD操作* @author jiangge*/
public class ManageEmployee
{private static SessionFactory factory;public static void main(String[] args){try{factory = new Configuration().configure().buildSessionFactory();} catch (Throwable ex){System.err.println("Failed to create sessionFactory object." + ex);throw new ExceptionInInitializerError(ex);}ManageEmployee ME = new ManageEmployee();/* Add few employee records in database */Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);Integer empID3 = ME.addEmployee("John", "Paul", 10000);/* List down all the employees */ME.listEmployees();/* Update employee's records */ME.updateEmployee(empID1, 5000);/* Delete an employee from the database */ME.deleteEmployee(empID2);/* List down new list of the employees */ME.listEmployees();}/* Method to CREATE an employee in the database */public Integer addEmployee(String fname, String lname, int salary){Session session = factory.openSession();Transaction tx = null;Integer employeeID = null;try{tx = session.beginTransaction();Employee employee = new Employee(fname, lname, salary);employeeID = (Integer) session.save(employee);tx.commit();} catch (HibernateException e){if (tx != null)tx.rollback();e.printStackTrace();} finally{session.close();}return employeeID;}/* Method to READ all the employees */public void listEmployees(){Session session = factory.openSession();Transaction tx = null;try{tx = session.beginTransaction();List employees = session.createQuery("FROM Employee").list();for (Iterator iterator = employees.iterator(); iterator.hasNext();){Employee employee = (Employee) iterator.next();System.out.print("First Name: " + employee.getFirstName());System.out.print("  Last Name: " + employee.getLastName());System.out.println("  Salary: " + employee.getSalary());}tx.commit();} catch (HibernateException e){if (tx != null)tx.rollback();e.printStackTrace();} finally{session.close();}}/* Method to UPDATE salary for an employee */public void updateEmployee(Integer EmployeeID, int salary){Session session = factory.openSession();Transaction tx = null;try{tx = session.beginTransaction();Employee employee = (Employee) session.get(Employee.class, EmployeeID);employee.setSalary(salary);session.update(employee);tx.commit();}catch (HibernateException e){if (tx != null)tx.rollback();e.printStackTrace();} finally{session.close();}}/* Method to DELETE an employee from the records */public void deleteEmployee(Integer EmployeeID){Session session = factory.openSession();Transaction tx = null;try{tx = session.beginTransaction();Employee employee = (Employee) session.get(Employee.class, EmployeeID);session.delete(employee);tx.commit();}catch (HibernateException e){if (tx != null)tx.rollback();e.printStackTrace();} finally{session.close();}}
}



执行结果,IDE的Console输出:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?)
Hibernate: insert into EMPLOYEE (first_name, last_name, salary) values (?, ?, ?)
Hibernate: select employee0_.id as id0_, employee0_.first_name as first2_0_, employee0_.last_name as last3_0_, employee0_.salary as salary0_ from EMPLOYEE employee0_
First Name: Zara  Last Name: Ali  Salary: 1000
First Name: Daisy  Last Name: Das  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000
Hibernate: select employee0_.id as id0_0_, employee0_.first_name as first2_0_0_, employee0_.last_name as last3_0_0_, employee0_.salary as salary0_0_ from EMPLOYEE employee0_ where employee0_.id=?
Hibernate: update EMPLOYEE set first_name=?, last_name=?, salary=? where id=?
Hibernate: select employee0_.id as id0_0_, employee0_.first_name as first2_0_0_, employee0_.last_name as last3_0_0_, employee0_.salary as salary0_0_ from EMPLOYEE employee0_ where employee0_.id=?
Hibernate: delete from EMPLOYEE where id=?
Hibernate: select employee0_.id as id0_, employee0_.first_name as first2_0_, employee0_.last_name as last3_0_, employee0_.salary as salary0_ from EMPLOYEE employee0_
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000


MySQL数据库数据:

mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
|  1 | Zara       | Ali       |   5000 |
|  3 | John       | Paul      |  10000 |
+----+------------+-----------+--------+
2 rows in set


參考文献:

1、英文: http://www.tutorialspoint.com/hibernate/hibernate_quick_guide.htm  

2、中文:http://blog.csdn.net/zs234/article/details/9212045 入门系列文章



==================我是没用得分隔线====================================================

Hibernate框架的使用步骤:
1、创建Hibernate的配置文件(hibernate.cfg.xml)
2、创建持久化类,即事实上例须要保存到数据库中的类(User.java)
3、创建对象-关系映射文件(User.hbm.xml)

4、通过Hibernate API编写訪问数据库的代码



Hibernate配置文件
        Hibernate配置文件从形式来讲有两种基本的格式:
  • 一种是Java属性文件,即*.properties,这样的配置格式主要定义连接数据库须要的參数
  • 另一种是XML格式的文件,这样的文档除了能够定义连接数据库须要的參数还能够定义程序中用的映射文件。所以普通情况下使用XML格式的配置文档。


映射的概念
    映射即对象关系映射(Object Relational Mapping)ORM的实现目的就是将对象数据保存到数据库中,同一时候能够将数据库数据读入对象中,    这样开发者就能够将对数据库数据的操作转化为对这些对象的操作。

注解配置基本映射实例 :
    除了XML方式(User.hbm.xml)配置映射外,还能够通过给类文件加入�注解的方式配置映射,比如:
          @Entiey
          @Table(name="user")
   很多其它内容请英文keyword搜索「hibernate annotations tutorial」


关系映射分类

       关系映射即在基本映射的基础上处理多个相关对象和多个相关表之间联系的映射。关系映射从相应关系的角度能够分为例如以下七种类型:
一对一单向关联
一对一双向关联
一对多单向关联
多对一单向关联
一对多双向关联
多对多单向关联

多对多双向关联




转载于:https://www.cnblogs.com/yxwkf/p/3839643.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/420774.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

二、Merge sort

1 问题 2 算法 2.1 伪代码 2.2 算法思想 2.3 手工演示 2.4 Python实现 # -*- coding: utf-8 -*- import sysdef merge(A, p, q, r):n1 q - p 1n2 r - qL [0] * (n1 2)R [0] * (n2 2)for i in range(1, n11):L[i] A[pi-1]for j in range(1, n21):R[j] A[qj]L[n11] 6…

三、递归树分析法

1 问题 2 解决思路 使用递归树猜想一个上界&#xff0c;使用归纳法证明上界也是下界。 2.1 使用递归树&#xff08;recursion tree&#xff09;猜想结论&#xff08;不严谨&#xff09; 使用递归树两点&#xff1a;1⃣️逐行展开&#xff1b;2⃣️逐行相加&#xff1b; 逐行…

html5input表单标签新属性

初探h5一&#xff0c;h5 新增表单类型二&#xff0c;新增表单属性三&#xff0c;code demo一&#xff0c;h5 新增表单类型 •email 邮箱地址•url 网络地址•number 数字框•range 滑块•Date pickers (date, month, week, time, datetime, datetime-local) 日期时间框•search…

关于java的JIT知识

1.JIT的工作原理图 工作原理 当JIT编译启用时&#xff08;默认是启用的&#xff09;&#xff0c;JVM读入.class文件解释后&#xff0c;将其发给JIT编译器。JIT编译器将字节码编译成本机机器代码。 通常javac将程序源码编译&#xff0c;转换成java字节码&#xff0c;JVM通过解释…

Storage 使用

关于web项目数据存储1. 存储种类2. localStorage/sessionStorage2.1 概念2.2 api的使用3. 学生curd测试localStorage针对客户端存储讲 ——storage1. 存储种类 1. 分为服务器端和客户端的存储 2. 服务器端&#xff1a;1. 内存存储(临时)application session request pageConte…

spring 基于xml方式配置aop

目录什么是aop模拟aop配置什么是aop 什么是aop 作用 在程序运行期间&#xff0c;在不修改源码的情况下对方法进行功能增强 优势 减少重复代码 提高开发效率 并且便于开发2.aop关键概念 模拟aop 目标接口 package com.lovely.proxy.aop;public interface TargetInterface …

3389爆破DUBrute_2.1

3389专业爆破 DUBrute_2.1.zip http://pan.baidu.com/s/1pJE0t5L转载于:https://www.cnblogs.com/lieyan/p/3859696.html

h5 server send event(sse)

1. sse概述 概念&#xff1a; H5支持使用JS脚本不间断的访问服务器(推送)轮询: 页面使用js的定时器&#xff0c;定时发送请求查询最新数据 使用js将最新数据加载至页面 每发送一次数据&#xff0c;需要建立新的连接 时间间隔由客户端决定 优点&#xff1a;不需要刷新页面、实…

sublime text3下BracketHighlighter的配置方法

st3的配置方法和st2是有区别的&#xff0c;所以网上搜索到的方法大多不能用&#xff0c;我google之后总结了一下。 一、 1、在st3中按preferences-->package settings-->Bracket highlighter-->Bracket settings-Default打开配置文件。 2、将配置文件信息全选复制一份…

利用spring注解创建bean

spring注解spring 原始注解1.1 Component注解1.2 Controller,Service,Repository同上1.3 注解方式依赖注入spring 新注解1. 用来解析配置类&#xff0c;利用配置类替代xml注解代替了xml的繁琐配置 spring 原始注解 1.1 Component注解 <!--spring 使用注解创建对象 compone…

文本分类--普通分类

1 基本概念 文本分类 文本分类&#xff08;text classification&#xff09;&#xff0c;指的是将一个文档归类到一个或多个类别的自然语言处理任务。文本分类的应用场景非常广泛&#xff0c;包括垃圾邮件过滤、自动打标等任何需要自动归档文本的场合。 文本分类在机器学习中属…