Hibernate

Hibernate的使用:

  1. 导包

  2. 配置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 name="foo">
    		<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=UTC</property>
    		<property name="hibernate.connection.username">root</property>
    		<property name="hibernate.connection.password">521314</property>
    		<property name="show_sql">true</property>
    		<property name="format_sql">true</property>
    		<property name="hibernate.connection.autocommit">true</property>
    		<property name="hibernate.current_session_context_class">thread</property>
    		<mapping resource="com/xdd/hibernate/model/User.hbm.xml"></mapping>
    	</session-factory>
    </hibernate-configuration>
    
  3. 配置类的映射为文件User.hbm.xml

    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="com.xdd.hibernate.model.User" table="user">
    	   <id name="id" column="id">
    	       <generator class="native"></generator>
    	   </id>
    	   <property name="name"></property>
    	   <property name="password"></property>
      </class>
    </hibernate-mapping>
    
  4. 测试保存数据

    //1:读取hibernate的核心配置文件
    	Configuration cfg=new Configuration().configure();
    //2:创建会话工厂
    	SessionFactory factory=cfg.buildSessionFactory();
    //3:创建会话
    	Session session=factory.openSession();
    //4:开启事务
    	Transaction transaction=session.getTransaction();
    		transaction.begin();
    		User user=new User("xdd","123");
    //保存数据
    		session.save(user);
    		transaction.commit();
    //关闭会话
    		session.close();
    		factory.close();
    

  • Hibernate配置文件有两种hibernate.cfg.xmlhibernate.properties
    ----- 1:new Configuration();读取hibernate.properties;
    ----- 2: new Configuration().configure();读取hibernate.cfg.xml;
  • 添加表的映射文件的方法
    ----- 1:在hibernate.cfg.xml中配置< mapping resource=“com/xdd/hibernate/model/User.hbm.xml”/>
    ----- 2:调用Configuration的addResource()方法;cfg.addResource(“com/xdd/hibernate/model/User.hbm.xml”);
    ----- 3:调用Configuration的addClass()方法;cfg.addClass(User.class);
  • 获取session对象的方法
    ----- 1:调用SessionFactory的openSession()方法;
    ----- 2:调用SessionFactory的getCurrentSession()方法;
    但必须在hibernate.cfg,xml中配置< property name=“hibernate.current_session_context_class”>thread< /property>

Session的常用方法

  1. save(Oblect obj)(不需要添加事务)
    把对象添加到数据
  2. get(Class class,int id)
    通过id获取对象,若id不存在则返回null
  3. load
    通过id获取对象,若id不存在则报错

getload的区别:
----get方法直接加载数据库;
----load方法返回一个代理对象,只有用到时才会加查询数据库


  1. update
    1:先获取需要更新的对象,然后设置需要更新的属性,再调用update()方法
    2:调用saveOrUpdate(Object obj)方法,若该对象存在id,则执行更新语句,否则执行插入语句

  2. delete
    1:先获取需要删除的对象,然后调用delete()方法
    2:先创建一个对象,然后设置id,再调用delete()方法

Query && Criteria && SQLQuery

  1. HQL:

    Query query=session.createQuery("from User where name=? and password=?");
    query.setParameter(0."xx");
    query.setParameter(1,"123");
    User user=query.uniqueResult();//uniqueResult()返回一行数据
    
  2. 分页查询:

    //分页查询
    Query query=session.createQuery("from User");
    query.setFirstResult(0);
    query.setMaxResult(3);
    List list=query.list();//list()返回多行数据
    
  3. Criteria
    1:
    //创建查询对象
    Criteria criteria=session.createCriteria(User.class);
    //添加查询条件,gt大于,ge大于等于,lt小于,le小于等于,like
    criteria.add(Restrictions.eq(“name”,“xx”));
    criteria.add(Restrictions.eq(“password”,“xx”));
    User user=criteria.uniqueResult();
    2:排序
    Criteria criteria=session.createCriteria(Customer.class);
    criteria.addOrder(org.hibernate.criterion.Order.desc/asc(“id”));

xx.hbm.xml映射文件

  1. 设置class标签的dynamic-insert与dynamic-update可以动态的插入或者更新

  2. Date类型property标签如果不写type,则数据库默认是datetime(年月日时分秒)
    如果写type是date,则数据库显示date类型(年月日)
    如果写type是time,则数据库显示time类型(时分秒)

  3. hibernate实体类的三种状态
    瞬时状态(transient):session没有缓存,数据库没记录,oid没值
    持久状态(persistent):session有缓存,数据库有记录,oid有值
    脱管状态(detached):session没有缓存,数据库有记录,oid有值

  4. 一对多数据的保存(用户表和订单表的关系)

    Order.hbm.xml

    <hibernate-mapping package="com.xdd.hibernate.model">
     	<class name="com.xdd.hibernate.model.Order" table="t_order">
    		 <id name="id">
      			  <generator class="native"></generator>
    		 </id>
    		 <property name="name"></property>
    		 <many-to-one name="customer" class="Customer" column="customer_id"></many-to-one>//customer_id表示外键
     	 </class>
    </hibernate-mapping>
    

    Customer.hbm.xml

    <hibernate-mapping package="com.xdd.hibernate.model">
    	<class name="Customer" table="t_customer" >
    	    <id name="id">
      			  <generator class="native"></generator>
    	   </id>
    	   <property name="name"></property>
    	   <set name="orders" inverse="false" >
    		     <key column="customer_id"></key>
     		   <one-to-many class="Order" ></one-to-many>
    	  </set>
     	</class>
    </hibernate-mapping>
    
  5. 级联(cascade)保存更新删除
    1:save-update:级联保存和更新,在保存用户的同时保存订单

     < set name="orders" inverse="false" cascade="save-update">
    

    2:delete级联删除,删除用户的同时删除对应的订单

    < set name="orders" inverse="false" cascade="delete">
    

    3:delete-orphan,不删除用户,只删除订单

  6. 多对多数据的保存(学生和老师)

    Student.hbm.xml

    <hibernate-mapping package="com.xdd.hibernate.model2">
    	<class name="Student" table="t_student">
    		<id name="sid" column="id">
     		 	 <generator class="native"></generator>
    		</id>
      		<property name="name"/>
    		<set name="teachers" table="t_student_teacher" cascade="save-update" >
       			 <key column="sid"></key>
    	   		 <many-to-many class="Teacher" column="tid"></many-to-many>
    		</set>
    	 </class>
    </hibernate-mapping>
    

    Teacher.hbm.xml

    <hibernate-mapping package="com.xdd.hibernate.model2">
      <class name="Teacher" table="t_teacher">
            <id name="tid" column="id">
    		    <generator class="native"></generator>
    	    </id>
    	    <property name="name"/>
    	  	<set name="students" table="t_student_teacher">
       			<key column="tid"></key>
      			<many-to-many class="Student" column="sid"></many-to-many>
     		</set>
      </class>
    </hibernate-mapping>
    

    –其中sid和tid表示中间表Student和Teacher的关系

  7. 加载策略

    1:类级别加载策略:在class标签中加入lazy属性,则执行load方法时变成即时记载,不是用到在查数据库
    2:set关联级别加载策略:默认查询(Student)时,不会查询寻对应的(Teacher),在set标签下设置lazy属性为false可实现同时加载
    3:fecth:在set标签中设置fecth属性为join(subselect/select)

  8. HQL 命名查询(也就是将hql语句写在映射文件中)
    1:局部:在xxx.hbm.xml中的class标签下添加< query>标签,通过Session的getNameQuery(“包名+query的标签名”);
    2:全局:在xxx.hbm.xml的hibernate-mapping下添加< query>标签,通过Seesion的getNameQuery(“query的标签名”)

Hibernate整合C3P0

  1. 导入c3p0的jar包

  2. 在hibernate.cfg.xml中配置c3p0连接池的数据:

     <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</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>
    

悲观锁 && 乐观锁

1:悲观锁:

  1. 读锁(共享锁):在sql语句后添加lock in share mode
    select *from table lock in share mode;
  2. 写锁(排他锁):在sql语句后面添加for update
    select *form table for update(锁表)
    select *from table where id=1 for update;(锁行 )
    HQL语句后面不能写for update,需要调用Query的setLockOptions();

2:乐观锁:

  • 在实体类里面添加一个version字段
  • 在实体类的映射文件中添加标签< version>

Hibernate整合log4j

  1. 添加jar包:log4j-1.2.16.jar,slf4j-api-1.6.1.jar,slf4j-log4j12-1.7.2.jar
  2. 将hibernate.jar包下的log4j.properties文件添加到项目
  3. 获取Logger对象:Logger log=LoggerFactory.getLogger(Student.class);

二级缓存Ehcacher整合

  1. 导包:

    backport-util-concurrent.jar
    commons-logging.jar
    ehcache-1.5.0.jar

  2. 在hibernate的配置文件中配置开启和提供商

    <!--开启二级缓存-->
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <!--配置二级缓存提供商-->
    <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
    
  3. 在hibernate中配置类和集合缓存

    //配置类缓存
    <class-cache class="com.xdd.hibernate.model.User" usage="read-only"></class-cache>
    //配置集合缓存
    <class-cache class="com.xdd.hibernate.model.User" usage="read-only"></class-cache>
    <collection-cache collection="com.xdd.hibernate.model.User" usage="read-only"></collection-cache>
    
  4. 导入ehcache.xml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值