hibernate基本配置

ORM

ORM(Object Relation Mapping)对象关系映射。是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将java程序中的对象自动持久化到关系数据库中。本质上就是将数据从一种形式转换到另外一种形式。

ORM优势

ORM框架可以让我们减少乏味的代码,更加的面向对象的设计,更好的性能,更好的移植性。

原理:
1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件
2.由hibernate.cfg.xml中的<mapping resource="com/xx/User.hbm.xml"/>读取并解析映射信息
3.通过config.buildSessionFactory();//创建SessionFactory
4.sessionFactory.openSession();//打开Sesssion
5.session.beginTransaction();//创建事务Transation
6.persistent operate持久化操作
7.session.getTransaction().commit();//提交事务
8.关闭Session
9.关闭SesstionFactory

创建持久化类

pojo: Plain Ordinary Java Object(无格式的Java对象)
Hibernate对pojo的要求:
–  属性要有对应的get和set方法
–  要有无参数的默认构造方法
–  不要使用final进行修饰

             hibernate配置文件示例
<?
xml version="1.0" encoding="UTF-8"?> <!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> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///test</property> <property name="connection.username">root</property> <property name="connection.password">lanxum</property> <!-- 方言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 数据库连接池 --> <property name="hibernate.c3p0.max_size">2</property> <property name="hibernate.c3p0.min_size">2</property> <property name="hibernate.c3p0.timeout">5000</property> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">false</property> <!-- 控制台显示sql --> <property name="hibernate.show_sql">true</property> <!-- 线程 --> <property name="hibernate.current_session_context_class">thread</property> <!-- 配置映射文件 --> <mapping resource="com/peng/pojo/User.hbm.xml"/> </session-factory> </hibernate-configuration>

运行hibernate

Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();        
SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);    

Session session = factory.getCurrentSession();
session.beginTransaction();
User user
= new User(); user.setUserName("hibernate"); user.setPassword("123"); session.save(user); session.getTransaction().commit();
原文地址:https://www.cnblogs.com/fudapeng/p/3845256.html