Hibernate学习笔记

Hibernate学习笔记

Hibernate是什么:

<span>Hibernate学习笔记</span>

<span>Hibernate学习笔记</span>

Hibernate 架构:

<span>Hibernate学习笔记</span>


<span>Hibernate学习笔记</span>



下载、安装、必要的 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格式的配置文档。


映射的概念
:

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

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


关系映射分类

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

一对一单向关联

一对一双向关联

一对多单向关联

多对一单向关联

一对多双向关联

多对多单向关联

多对多双向关联

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/119043.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • Android制作字符串表格String.xml转EXCEL工具

    Android制作字符串表格String.xml转EXCEL工具publicstaticListgetAllExternalSdcardPath(){ListPathList=newArrayList();StringfirstPath=Environment.getExternalStorageDirectory().getPath();Log.d(TAG,”getAllExter

    2022年8月22日
  • Adobe Dreamweaver 2021下载安装教程

    Adobe Dreamweaver 2021下载安装教程软件介绍AdobeDreamweaver2021是专业的网站设计软件,使用可为处理各种Web文档提供灵活的环境。Dreamweaver2021一款非常受欢迎的网页设计软件,是该系列的全新版本,可以帮助广大学生、程序员制作出精美的网页,在全新的Dreamweaver2021版本中,在其优秀的功能上带来了更多的改进和优化,拥有无缝实时视图编辑功能,在以往用户需要切换到单独的编辑模式来预览网站,现在仅需一键即可预览和更改网页,还支持Windows的多显示器方案,为用户带来了更加整洁主界面,并且修改了十多个

    2022年7月14日
  • 网站访问人数太多,怎么才能进入_网址挖掘

    网站访问人数太多,怎么才能进入_网址挖掘老规矩,先上代码:#coding=utf-8importosimportrequestsimporttimefromPILimportImagefromioimportBytesIOfromlxmlimportetree#先定义一个opener函数:defopen_mn_web(url):try:headers=…

    2022年10月28日
  • 从“做事用人”到“用人做事”[通俗易懂]

    从“做事用人”到“用人做事”[通俗易懂]阿里张勇:从“做事用人”到“用人做事”商业管理今年十一月底,阿里巴巴进行了一年一度的组织架构调整,在这次调整中,阿里云升级成为阿里云智能;天猫升级为“大天猫”,并形成了三个事业群。12月时,阿里巴巴集团CEO张勇,在阿里青年干部培训营上,谈了他对这次组织架构升级的思考。36氪发表了张勇的讲话全文,我们从中为你选取了他的5个观点。第一,从“做事用人”到“用人做事”。这是马云给张勇的…

    2022年10月31日
  • egg yolk_人类蛋白数据库

    egg yolk_人类蛋白数据库欢迎关注”生信修炼手册”!直系同源蛋白的预测在系统发育,比较基因组学等多个领域都占用重要地位,COG数据库开创了同源蛋白数据库的先河,后续又不断有新的数据库涌现,而eggNOG就是目前使…

    2022年10月29日
  • sbc音频编解码是什么_人工智能fpga算法工程师

    sbc音频编解码是什么_人工智能fpga算法工程师转自:https://blog.csdn.net/wzz4420381/article/details/48676921原作者:wzz44203811.SBC算法简介SBC是subbandcode的缩写,也可称为子带编码 在A2DP协议中,SBC算法是默认支持的 蓝牙SBC算法是一种以中等比特率传递高质量音频数据的低计算复杂度的音频编码算法1.1算法基本框图SB…

    2022年9月11日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号