2016-03-13 119 views
0

我在SPring MVC + JPA + SQL Server上構建了一個小應用程序。出於某些原因,我必須在應用程序中進行一些實體更改,並且必須手動將某些數據從舊數據庫遷移到新數據庫(具有不同的模式)。我遷移所有的數據後,我有這樣的錯誤:重複鍵值JPA

13:47:26.191 [HTTP-NIO-8080-EXEC-1] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - PRIMARY KEY約束 'PK__GLJourna__3213E83F741BD595' 的衝突。無法在對象'dbo.GLEntry'中插入重複鍵。重複鍵值是(34903)。

這是我的實體:

​​3210

我的猜測是,我接受,因爲默認的ID註釋@Id @GeneratedValue的此錯誤消息。

我該如何解決?我如何以自動從DB獲取最新ID的方式生成ID?

回答

0

我的問題最簡單的辦法是改變註釋實體

從:更改 @Id @GeneratedValue 到: @Id @GeneratedValue(strategy = GenerationType.AUTO)

0

您可以使用數據庫的順序功能來獲取唯一的ID,這將始終是最新的和最新的ID。

使用鏈接瞭解更多信息http://stackoverflow.com/questions/2595124/java-jpa-generators-sequencegenerator

+0

我該怎麼做?我用這個:'@Id @SequenceGenerator(name =「id_generator」,sequenceName =「SEQUENCE_NAME」,allocationSize = 1) @GeneratedValue(generator =「id_generator」,strategy = GenerationType.SEQUENCE)''但結果相同 – Irakli

+0

http: //stackoverflow.com/questions/2595124/java-jpa-generators-sequencegenerator,請參閱鏈接,希望它能解決您的問題。 –

0

嘗試這樣的事情在你的數據庫

CREATE SEQUENCE "ABC"."MY_SEQ" MINVALUE 0 MAXVALUE 2147483647 INCREMENT BY 1 START WITH 9130 CACHE 50 ORDER NOCYCLE ; 
0

您可以通過使用自定義的邏輯從數據庫獲取最新的標識。示例我做了什麼來解決我的問題。它的工作原理與Hibernate -

@Id 
@Basic(optional = false) 
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="GeneratedId") 
@GenericGenerator(name="GeneratedId", 
        strategy="....GenerateId" 
) 
@Column(name = "ID", nullable = false) 
private Integer id; 

import org.hibernate.id.IdentityGenerator; 
... 
public class GenerateId extends IdentityGenerator { 
private static final Logger log = Logger.getLogger(GenerateId.class.getName()); 

@Override 
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { 
    String prefix = "M"; 
    Connection connection = session.connection(); 
    try { 

     PreparedStatement ps = connection 
       .prepareStatement("SELECT nextval ('seq_stock_code') as nextval"); 

     ResultSet rs = ps.executeQuery(); 
     if (rs.next()) { 
      int id = rs.getInt("nextval"); 
      String code = prefix + StringUtils.leftPad("" + id,3, '0'); 
      log.debug("Generated Stock Code: " + code); 
      return code; 
     } 

    } catch (SQLException e) { 
     log.error(e); 
     throw new HibernateException(
       "Unable to generate Stock Code Sequence"); 
    } 
    return null; 
}