2011-03-22 52 views
7

我寫我自己的IdGenerator:休眠:手動調用SequenceGenerator?

public class AkteIdGenerator implements IdentifierGenerator { 
    public Serializable generate(SessionImplementor session, Object object) 
     throws HibernateException { 
     // if custom id is set -> use this id 
     if (object instanceof SomeBean) { 
     SomeBean someBean = (SomeBean) object; 
     Long customId = someBean.getCustomId(); 
     if (customId != 0) { 
      return customId; 
     } 
     } 
     // otherwise --> call the SequenceGenerator manually 
     SequenceStyleGenerator sequenceGenerator ... 
    } 
} 

有誰知道我怎麼會從我的生成器類調用sequenceGenerator我通常可以每註解定義:

@GeneratedValue(
     strategy = GenerationType.SEQUENCE, 
     generator = "MY_SEQUENCE") 
@SequenceGenerator(
     allocationSize = 1, 
     name = "MY_SEQUENCE", 
     sequenceName = "MY_SEQUENCE_NAME") 

我會非常感激任何解決方案!

非常感謝,諾伯特

回答

6

您可以撥打eassly從發電機類SequenceGenerator。通過編寫這段代碼。 定製發生器類應該是

public class StudentNoGenerator implements IdentifierGenerator { 

public Serializable generate(SessionImplementor session, Object object)throws HibernateException { 

    SequenceGenerator generator=new SequenceGenerator(); 
    Properties properties=new Properties(); 
    properties.put("sequence","Stud_NoSequence"); 
    generator.configure(Hibernate.STRING, properties, session.getFactory().getDialect()); 
    return generator.generate(session, session); 

} 

}
在上面的代碼Stud_NoSequence是序列名稱,它shoulb被創建。在數據庫中絞合create sequence Stud_NoSequence; Hibernate.String是由SequenceGenerator類返回的類型。

和領域類是

import javax.persistence.Column; 
    import javax.persistence.Entity; 
    import javax.persistence.GeneratedValue; 
    import javax.persistence.Id; 
    @Entity 
    @org.hibernate.annotations.GenericGenerator(
    name = "Custom-generator", 
    strategy = "com.ssis.id.StudentNoGenerator" 
    ) 
    public class Student { 
@Id @GeneratedValue(generator = "Custom-generator") 
String rno; 
@Column 
String name; 
public String getRno() { 
    return rno; 
} 
public void setRno(String rno) { 
    this.rno = rno; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
    } 
0

你的職位是有幫助的,以更新序列的名稱。

因爲我每月使用一個序列,並且配置不會更新每個標識符的生成。

這裏是我的代碼:

@Override 
public Serializable generate(SessionImplementor sessionImplementator, 
     Object object) throws HibernateException { 
    Calendar now = Calendar.getInstance(); 
    // If month sequence is wrong, then reconfigure. 
    if (now.get(Calendar.MONTH) != SEQUENCE_DATE.get(Calendar.MONTH)) { 
     super.configure(new LongType(), new Properties(), 
       sessionImplementator.getFactory().getDialect()); 
    } 
    Long id = (Long) super.generate(sessionImplementator, object); 
    String sId = String.format("%1$ty%1$tm%2$06d", SEQUENCE_DATE, id); 
    return Long.parseLong(sId);// 1301000001 
}