2015-07-01 34 views
8

這裏是我的POJO類如何使用Hibernate來生成自定義ID,而它必須是表的主鍵

@Entity 

public class Department { 


@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY) 

@Column(name="Department_Id") 

private Integer deptId; 


@Column(name="Department_Name",unique=true,nullable=false) 
private String deptName; 


@Column(name="Department_Description") 
@NotNull 
private String deptDesc; 
    //geters and setters 

什麼,我想要的是部門標識必須是該密鑰必須這部表項的主鍵如DEP0001,DEP0002,DEP003

+0

http://supportmycode.com/2014/08/22/custom-id-generator-in-hibernate/ –

+0

什麼DB您正在使用? – mrh

+0

我正在使用mysql –

回答

12

謝謝大家的迴應...... 終於我在我的Department類中做了一些改變,並且使用了一個類來生成id ........這裏是我的代碼

@Entity 
public class Department { 

@Id 
@GenericGenerator(name = "sequence_dep_id", strategy = "com.xyz.ids.DepartmentIdGenerator") 
@GeneratedValue(generator = "sequence_dep_id") 
@Column(name="Department_Id") 
private String deptId; 

@Column(name="Department_Name",unique=true,nullable=false) 
private String deptName; 


@Column(name="Department_Description") 
@NotNull 
private String deptDesc; 

//getters and setters 

DepartmentIdGenerator.java

package com.xyz.ids; 

import java.io.Serializable; 
import java.sql.*; 
import org.hibernate.HibernateException; 
import org.hibernate.engine.spi.SessionImplementor; 
import org.hibernate.id.IdentifierGenerator; 

public class DepartmentIdGenerator implements IdentifierGenerator{ 

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

     String prefix = "DEP"; 
     Connection connection = session.connection(); 

     try { 
      Statement statement=connection.createStatement(); 

      ResultSet rs=statement.executeQuery("select count(Department_Id) as Id from demo.Department"); 

      if(rs.next()) 
      { 
       int id=rs.getInt(1)+101; 
       String generatedId = prefix + new Integer(id).toString(); 
       System.out.println("Generated Id: " + generatedId); 
       return generatedId; 
      } 
     } catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     return null; 
    } 

} 
+0

eclipse抱怨說在持久化單元 – erickdeoliveiraleal

+0

中沒有定義名爲的生成器,您是否也在persistence.xml中定義了它,或者它是eclipse中的錯誤? – erickdeoliveiraleal

+2

缺少這個是當我們從表中刪除一個條目並嘗試創建一個新條目。我們可以違反主鍵約束! –

相關問題