hibernate对象三种状态

hibernate里对象有三种状态:
1.Transient 瞬时 :对象刚new出来,还没设id,设了其他值。
2.Persistent 持久:调用了save()、saveOrUpdate(),就变成Persistent,有id
3.Detached 脱管 : 当session close()完之后,变成Detached。
在这里插入图片描述

创建数据库对象:CustomerBean

CREATE TABLE `customerbean` (
  `CID` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(255) DEFAULT NULL,
  `NO` int(11) DEFAULT NULL,
  `SCORE` bigint(20) DEFAULT NULL,
  `MONEY` double DEFAULT NULL,
  `REGISTERDATE` date DEFAULT NULL,
  `LOGINTIME` datetime DEFAULT NULL,
  PRIMARY KEY (`CID`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

CustomerBean类

package com.happybks.hibernate.hibernatePro.beans;
import java.sql.Date;
import java.sql.Timestamp;
public class CustomerBean {
 
 private String name;
 private Integer no;
 private Integer cid;
 private Long score;
 private double money;
 private Date registerDate;
 
private Timestamp loginTime;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getNo() {
  return no;
 }
 public void setNo(Integer no) {
  this.no = no;
 }
 public Integer getCid() {
  return cid;
 }
 public void setCid(Integer cid) {
  this.cid = cid;
 }
 public Long getScore() {
  return score;
 }
 public void setScore(Long score) {
  this.score = score;
 }
 public double getMoney() {
  return money;
 }
 public void setMoney(double money) {
  this.money = money;
 }
 public Date getRegisterDate() {
  return registerDate;
 }
 public void setRegisterDate(Date registerDate) {
  this.registerDate = registerDate;
 }
 public Timestamp getLoginTime() {
  return loginTime;
 }
 public void setLoginTime(Timestamp loginTime) {
  this.loginTime = loginTime;
 }
 public CustomerBean() {
  super();
 }
 @Override
 public String toString() {
  return "CustomerBean [name=" + name + ", no=" + no + ", cid=" + cid + ", score=" + score + ", money=" + money
    + ", registerDate=" + registerDate + ", loginTime=" + loginTime + "]";
 }
}
 

CustomerBean.hbm.xml

<hibernate-mapping>
    <class name="com.happybks.hibernate.hibernatePro.beans.CustomerBean" table="CUSTOMERBEAN">
        <id name="cid" type="java.lang.Integer">
            <column name="CID" />
            <!-- 指定主键的生成方式:native使用数据库本地的生成方式-->
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="no" type="java.lang.Integer">
            <column name="NO" />
        </property>
        <property name="score" type="java.lang.Long">
            <column name="SCORE" />
        </property>
        <property name="money" type="double">
            <column name="MONEY" />
        </property>
        <property name="registerDate" type="java.sql.Date">
            <column name="REGISTERDATE" />
        </property>
        <property name="loginTime" type="java.sql.Timestamp">
            <column name="LOGINTIME" />
        </property>
    </class>
</hibernate-mapping>

hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
    <!-- 配置连接数据库的信息 -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world?serverTimezone=UTC&amp;characterEncoding=utf8&amp;useUnicode=true&amp;useSSL=false</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">123456</property>
      <!-- 指定数据库方言 -->
   <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
   <!-- 显示Hibernate持久化操作所生成的SQL -->
   <property name="show_sql">true</property>
   <!-- 将SQL脚本进行格式化后再输出 -->
   <property name="format_sql">true</property>
    <!-- 根据需要自动创建数据表 -->
   <property name="hbm2ddl.auto">update</property> 
   <!-- 設置Hibernate的事務隔離級別 -->
   <property name="connection.isolation">2</property>
      <!-- 需要关联的Hibernate映射文件 .hbm.xml -->
      <mapping resource="com/happybks/hibernate/hibernatePro/beans/CustomerBean.hbm.xml"/>
    
    </session-factory>
</hibernate-configuration>

测试类:

package com.happybks.hibernate.hibernatePro;

import java.sql.Date;
import java.sql.Timestamp;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;

import com.happybks.hibernate.hibernatePro.beans.CustomerBean;
public class HibernateTest1 {
  @Test
  public void test1(){
  //1.创建一个SessionFactory对象
  SessionFactory sessionFactory=null;
  //1.1创建Configuration对象:对应包含Hibernate的基本配置信息(cfg)和对象关系映射信息(hbm)
  Configuration configuration=new Configuration().configure();
  //hibernate 3.x版本的SessionFactory的创建方式,4.X被Deprecated,5.x又再次回归。
  //new Configuration().buildSessionFactory();
  //1.2 创建一个ServiceRegistry对象:这个对象是从Hibernate 4.x开始新增加入的
  //hibernate的任务配置和服务需要在该对象中注册后才能有效。
  //hibernate 4.x版本中的ServiceRegistry创建方式:
  //ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
  //hibernate 5.x版本中的ServiceRegistry创建方式:
  ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
  System.out.println(CustomerBean.class.getCanonicalName());
  //  Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(CustomerBean.class)
//    .addAnnotatedClassName(CustomerBean.class.getName()).addResource("com/happybks/hibernate/hibernatePro/beans/CustomerBean.hbm.xml")
//    .getMetadataBuilder().applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
//    .build();
//
//  //1.3 创建sessionFactory
//  //hibernate 4.x版本中的sessionFactory创建方式: sessionFactory=configuration.buildSessionFactory(serviceRegistry);
//  //hibernate 5.x版本中的sessionFactory创建方式:
//  sessionFactory=metadata.getSessionFactoryBuilder().build();
  sessionFactory=configuration.buildSessionFactory(serviceRegistry);
  //2. 创建一个Session对象
  Session session=sessionFactory.openSession();
  
  //3. 开启事务
  Transaction transaction=session.beginTransaction();
  //4. 执行保存操作。把对象保存到数据库
  CustomerBean bean=new CustomerBean();
  bean.setName("HappyBKs");
  bean.setNo(314);
  bean.setMoney(20688.68);
  bean.setScore(98765432123456789L);
  bean.setRegisterDate(new Date(new java.util.Date().getTime()));
  bean.setLoginTime(Timestamp.valueOf("2017-01-08 12:00:00"));
  session.save(bean);

  CustomerBean bean1=(CustomerBean) session.get(CustomerBean.class, 1);
  System.out.println(bean1.getName());
  //5. 提交事务。
  transaction.commit();
  
  //6. 关闭Session
  session.close();
  
  //7. 关闭SessionFactory对象。
  sessionFactory.close();
  }

运行结果:
Hibernate:
insert
into
CUSTOMERBEAN
(NAME, NO, SCORE, MONEY, REGISTERDATE, LOGINTIME)
values
(?, ?, ?, ?, ?, ?)
Hibernate:
select
customerbe0_.CID as CID1_0_0_,
customerbe0_.NAME as NAME2_0_0_,
customerbe0_.NO as NO3_0_0_,
customerbe0_.SCORE as SCORE4_0_0_,
customerbe0_.MONEY as MONEY5_0_0_,
customerbe0_.REGISTERDATE as REGISTER6_0_0_,
customerbe0_.LOGINTIME as LOGINTIM7_0_0_
from
CUSTOMERBEAN customerbe0_
where
customerbe0_.CID=?

总结:
hibernate对象三种状态的区分关键在于:
  a)有没有id
  b)id在数据库中有没有
  c)在内存中有没有(session缓存)

三种状态:

a) transient :内存中一个对象,没id,缓存中也没有
  b)persistent:内存中有对象,缓存中有,数据库中有(id)
  c)detachd:内存有对象,缓存没有,数据库有

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值