Hibernate_005_ID生成策略_XML_Annotation

本文介绍了Hibernate框架中主键生成的两种方式:XML配置与注解配置。详细讲解了如何使用native策略及如何通过@SequenceGenerator指定数据库中的序列名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XML方式:

1、Student.hbm.xml文件配置(generator class 可以有多种,常用的是native、uuid),native是交由数据库来创建主键,oracle是通过sequence。

<hibernate-mapping package="com.jimmy.hibernate.model">
    <class name="Student">
        <id name="id" >
        	<generator class="native"></generator>
        </id>
        <property name="age"/>
        <property name="name"/>
    </class>
</hibernate-mapping>


 Annotation方式:

在主键对应的getId()方法上添加@id  ,@GeneratedValue(默认值是native)

         @Id
	@GeneratedValue
	public int getId() {
		return id;
	}

上面的代码在数据库产生的seq是系统默认创建的,名字统一都叫Hibernate_Sequence,并且多个类都是用这个SEQ。若要指定生成一个SEQ,则需要通过@SequenceGenerator (序列生成器),具体代码如下:

package com.jimmy.hibernate.model;

import java.util.Date;

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType;

import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; import org.hibernate.classic.Session;

@Entity @SequenceGenerator(name="teacherSEQ",sequenceName="teacherSEQ_DB")//定义一个名叫“teacherSEQ”序列生成器,在数据库中的序列名"teacherSEQ_DB"

public class Teacher {  private int id;  private String name;  private String title;  private Date birthday;    @Temporal(TemporalType.DATE)  public Date getBirthday() {   return birthday;  }  public void setBirthday(Date birthday) {   this.birthday = birthday;  }  @Id  @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="teacherSEQ")//采用sequence的策略,生成器用“teacherSEQ”  public int getId() {   return id;  }  public void setId(int id) {   this.id = id;  }  public String getName() {   return name;  }  public void setName(String name) {   this.name = name;  }  public String getTitle() {   return title;  }  public void setTitle(String title) {   this.title = title;  }  public void save(){   Configuration cf=new AnnotationConfiguration();   SessionFactory sf=cf.configure().buildSessionFactory();   Session session=sf.openSession();   session.beginTransaction();   session.save(this);   session.getTransaction().commit();   session.close();   sf.close();  } }



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值