Home Database Mysql Tutorial Hibernate基础-HelloWord

Hibernate基础-HelloWord

Jun 07, 2016 pm 04:09 PM
hibernate orm Base

1. ORM :ORM ( Object / Relation Mapping ): 对象 / 关系映射(理解) 1) ORM 主要解决对象 - 关系的映射 2) .ORM的思想:将关系数据库中表中的记录映射成为对象,以对象的形式展现,程序员可以把对数据库的操作转化为对对象的操作。 2. Hibernate 的 Hel

1. ORM :ORM (Object /Relation Mapping ): 对象/关系映射(理解) 1) ORM 主要解决对象 -关系的映射 2) .ORM的思想:将关系数据库中表中的记录映射成为对象,以对象的形式展现,程序员可以把对数据库的操作转化为对对象的操作。
2. Hibernate 的 HelloWord 1) . 加入 jar 包:加入到当前项目的 classpath 下 hibernate-release-4.2.4.F inal\lib\required\*.jar(所有的包) MySQL 的驱动mysql -connector -java -5.1.29 -bin.jar
2) . 配置 hibernate 的配置文件: hibernate.cfg.xml
①. 利用 hibernate 插件生成 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 > session -factory > hibernate-configuration>
②. 编辑 hibernate.cfg.xml 文件
I. 加入链接数据库的基本信息:
! -- 配置连接数据库的基本信息 --> property name ="connection.driver_class" >com.mysql.jdbc.Driver property > property name ="connection.username" >root property > property name ="connection.password" >123456 property > property name ="connection.url" >jdbc :mysql:///hibernate4property>
II. 配置 Hibernate 使用的数据库方言: 每一种数据库使用的基本语法会有细微的区别,例如分页 MySQL 使用 limit,而 Oracle 使用 rownum。这就需要告诉 Hibernate 底层使用的是哪一种数据库
! -- 配置 Hibernate 的数据库方言 --> property name ="dialect" >org.hibernate.dialect.MySQLInnoDBDialect property > 注意:方言对应的类来自于 hibernate-release- 4.2.4.Final\project\etc\hibernate.properties 中 III. 编辑 Hibernate 的一般属性
! -- 创建数据表的策略(了解,最多使用的值是 update) --> property name ="hbm2ddl.auto" >update property >
> create : 每次运行都会删除上一次的表 ,重新生成表 , 哪怕二次没有任何改变 > create -drop :会根据 .hbm.xml 文件生成表, 但是SessionFactory 一关闭, 表就自动删除 > update :最常用的属性值,也会根据 .hbm.xml 文件生成表 , 但若 .hbm.xml 文件和数据库中对应的数据表的表结构不同 , Hiberante 将更新数据表结构,但不会删除已有的行和列 > validate : 会和数据库中的表进行比较 ,.hbm.xml 文件中的列在数据表中不存在,则抛出异常

! -- 是否打印 SQL --> property name ="show_sql" >trueproperty>
! -- 是否格式化 SQL --> property name ="format_sql" >trueproperty>
3) . 编写实体类( POJO)及 Hibernate 映射文件: xxx.hbm.xml
I. 编写一个 POJO :必须包含一个 OID 字段和数据表主键对应;必须有一个无参数的构造器;为字段定义 getter、 setter;非 final 类
II. 由 hibernate 插件生成 xxx.hbm.xml 文件
注意:需要对文件进行简单的修改:修改主键生成方式(使用 id 的 generator 子节点的 class 属性配置主键的生成方式, native 表示使用数据库本地的方式来 生成主键, MySQL 会自动的选用 auto_increment,而 Oracle 则使用序列的方式)
generator class ="assigned" /> 修改为 generator class="native" />
III. 在 hibernate 配置文件(hiberante.cfg.xml )中关联 hibernate 持久化类的映射文件 mapping resource ="com/atguigu/hibernate/entities/News.hbm.xml" />
4) . 通过 Hibernate API 完成持久化操作
1. 创建 SessionFactory : Session 的工厂类。SessionFactory 是线程安全的,一般地,在一个 Java 应用中只有一个 SessionFactory 实例 Configuration configuration = new Configuration ().configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()) .buildServiceRegistry (); SessionFactory sessionFactory = configuration.buildSessionFactory (serviceRegistry );
2. 创建 Session : 表示 Hibernate 应用程序和数据库的一次会话 Session session = sessionFactory.openSession ();
3. 开启事务 Transaction transaction = session.beginTransaction ();
4. 执行持久化操作 //save //session.save (news );
//利用 OID 加载对象 News news2 = (News ) session.get (News.class , 1); System.out.println (news2 ); news2.setContent ("myBatis" );
5. 提交事务 transaction.commit ();
6. 关闭 Session session.close ();
7. 关闭 SessionFactory sessionFactory.close ();

★写测试类的时候一般采用注解更方便些: public class Testing { private SessionFactory sessionFactory ; private Session session ; private Transaction transaction = null ; @Before public void init (){ Configuration configuration = new Configuration ().configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings( configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory (serviceRegistry ); session = sessionFactory.openSession (); transaction = session.beginTransaction (); } @After public void destroy (){ transaction.commit (); session.close (); sessionFactory.close (); } @Test public void test (){ //测试部分 } }

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ORM framework Tortoise ORM in Python in practice ORM framework Tortoise ORM in Python in practice Jun 10, 2023 pm 06:05 PM

TortoiseORM is an asynchronous ORM framework developed based on the Python language and can be used to manage relational databases in Python asynchronous applications. This article will introduce how to use the TortoiseORM framework to create, read, update and delete data. You will also learn how to perform simple and complex queries from a relational database. Preparation Before starting this tutorial, you need to install Python (Python3.6+ is recommended) and install TortoiseOR.

How to use object-relational mapping (ORM) in PHP to simplify database operations? How to use object-relational mapping (ORM) in PHP to simplify database operations? May 07, 2024 am 08:39 AM

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

What is the ORM mechanism of Java Hibernate framework? What is the ORM mechanism of Java Hibernate framework? Apr 17, 2024 pm 02:39 PM

Hibernate is a JavaORM framework for mapping between Java objects and relational databases. Its ORM mechanism includes the following steps: Annotation/Configuration: The object class is marked with annotations or XML files, specifying its mapped database tables and columns. Session factory: manages the connection between Hibernate and the database. Session: Represents an active connection to the database and is used to perform query and update operations. Persistence: Save data to the database through the save() or update() method. Query: Use Criteria and HQL to define complex queries to retrieve data.

PHP Basics Tutorial: From Beginner to Master PHP Basics Tutorial: From Beginner to Master Jun 18, 2023 am 09:43 AM

PHP is a widely used open source server-side scripting language that can handle all tasks in web development. PHP is widely used in web development, especially for its excellent performance in dynamic data processing, so it is loved and used by many developers. In this article, we will explain the basics of PHP step by step to help beginners from getting started to becoming proficient. 1. Basic syntax PHP is an interpreted language whose code is similar to HTML, CSS and JavaScript. Every PHP statement ends with a semicolon; Note

What are the disadvantages of Hibernate ORM framework? What are the disadvantages of Hibernate ORM framework? Apr 18, 2024 am 08:30 AM

The HibernateORM framework has the following shortcomings: 1. Large memory consumption because it caches query results and entity objects; 2. High complexity, requiring in-depth understanding of the architecture and configuration; 3. Delayed loading delays, leading to unexpected delays; 4. Performance bottlenecks, in May occur when a large number of entities are loaded or updated at the same time; 5. Vendor-specific implementation, resulting in differences between databases.

How PHP object-relational mapping and database abstraction layers improve code readability How PHP object-relational mapping and database abstraction layers improve code readability May 06, 2024 pm 06:06 PM

Answer: ORM (Object Relational Mapping) and DAL (Database Abstraction Layer) improve code readability by abstracting the underlying database implementation details. Detailed description: ORM uses an object-oriented approach to interact with the database, bringing the code closer to the application logic. DAL provides a common interface that is independent of database vendors, simplifying interaction with different databases. Using ORM and DAL can reduce the use of SQL statements and make the code more concise. In practical cases, ORM and DAL can simplify the query of product information and improve code readability.

Object Relational Mapping (ORM) Basics: Understanding Doctrine ORM Object Relational Mapping (ORM) Basics: Understanding Doctrine ORM Jun 19, 2023 pm 03:43 PM

Object Relational Mapping (ORM) Basics: Understanding DoctrineORM When we develop applications, we need to operate on the database to store and retrieve data. However, it is inconvenient to use the original database query code directly. We need to establish a mapping relationship between objects and data. This is the role of ORM. ORM automatically maps and converts objects and database tables, allowing easy data manipulation, making our code easier to maintain. DoctrineORM is PHP

See all articles