1.字符串类主键
public class ID{
/**
* 获取一个新的不重复的ID
*
* @return 长整型数字
*/
public synchronized static BigDecimal next(){
String s = "";
String t = new SimpleDateFormat("yyMMddHHmmss").format(new Date(System.currentTimeMillis()));
if(!t.equals(time)){
time = t;
serial = (int)Math.round(Math.random()*5);
}
int max = (int) Math.pow(10, DIGIT);
if(++serial >= max){
try{
Thread.sleep(1000L);
}catch(InterruptedException e){}
return next();
}
s += serial;
while(s.length() < DIGIT){
s = "0" + s;
}
long a =Long.parseLong(time + s);
return BigDecimal.valueOf(a);
}
}
//主键ID字符串
String id = ID.next().toString();
2.数字类主键
第一步: 创建数据库
oracle的安装就不说了, 要注意的是表和字段名最好的全部大写. 不然hibernate连接查询时会报"标识符无效"的错误.
oracle里面设置主键自增需要用到sequence. 创建sequence的sql:
CREATE SEQUENCE TestIncrease_Sequence
INCREMENT BY 1 -- 每次加几个
START WITH 1 -- 从1开始计数
NOMAXVALUE -- 不设置最大值
NOCYCLE -- 一直累加,不循环
CACHE 10;
如果是用Powerdesign设计数据库的话, Powerdesign会自动为INTEGER类型的主键创建sequence, 命名格式为"S_表名".
第二步: 为hibernate生成映射文件
用myeclipse自动的逆向工程工具, 不能识别sequence自增的主键(这个不知道为什么). 所以逆向的时候需要自增的表选择native的自增方式. 在生成好的实体类中再写入sequence的annotation. 例如:
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")
@SequenceGenerator(name="SEQ_STORE", sequenceName="S_ORACLE",allocationSize = 1)
@Column(name = "ID", unique = true, nullable = false, precision = 6, scale = 0)
public Integer getId() {
return this.id;
}
@GeneratedValue是设置一个生成器,@SequenceGenerator就是设置主键自增了.sequenceName属性中指定使用哪个sequence. allocationSize = 1这个是指每次自增1, 不填的话自增值将是随机的.
如果是用xml的映射方式的话:
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="sequence">
<param name="sequence">pk</param>//pk为sequence名称
</generator>
</id>
在sequence属性中指定使用哪个sequence.
第三步:执行
在java中执行save操作, hibernate会输出以下sql语句:
Hibernate: select S_ORACLE.nextval from dual
Hibernate: insert into SCOTT.T_ORACLE (AGE, NAME, ID) values (?, ?, ?)
第一句是取出sequence里的下一个值, 第二句就是保存操作;