2012-06-16 2 views
-1

내 웹 서비스는 DB에 추가 할 데이터 목록을 가져온다.최대 절전 모드로 중복 레코드를 처리하는 방법

쓸 테이블은 3 fields : (id,userId,contactId)입니다. DB (userId,contactId)unique key입니다.

웹 서비스에서 중복 된 값 (userId,contactId)을 검색하는 경우 Java 측에서 예외를 처리해야하며 중복 예외가 발생한 경우 나머지 레코드를 추가해야합니다.

Here 코드를 사용하고 있습니다. i = 0, 라인 11, 12, 16, 21이 실행될

Session session = HibernateUtil.getSessionFactory().openSession(); 
Transaction transaction = null; 
try { 
    transaction = session.beginTransaction(); 

    for (int i=0; i<contactsToAdd.size(); ++i) 
    { 
     Contact contact = new Contact(userId, contactsToAdd.get(i)); 
     try 
     { 
      session.saveOrUpdate(contact);       // line 11 
      session.flush(); 
     } 
     catch (HibernateException e) 
     { 
      transaction.rollback();         // line 16 
//     e.printStackTrace(); 
     } 
     finally 
     { 
      session.clear();          // line 21 
     } 
    } 

    transaction.commit(); 
    return true; 
} 
catch (HibernateException e) { 
    transaction.rollback();             // line 29 
    e.printStackTrace(); 
} 
finally { 
    session.close();              // line 33 
} 
  • .
  • i = 1 인 경우 11, 12, 16, 21, 29, 30, 33 행이 실행됩니다.

이유를 이해해 주시겠습니까?

+2

는 관련 [SSCCE]을 게시하는 것이 좋습니다 (http://sscce.org/) 코드 ** **에 같음과 Gethashcode를 구현 가정 관련 코드가 사라지는 외부 사이트가 아닌 미래의 방문자에게 쓸모없는 질문을 던지십시오. –

답변

0

연락이 질문에 두 개의 관련 필드 인라인

Set<Contact> contacts = ...; 
for (int i=0; i<contactsToAdd.size(); ++i) 
{ 
    contacts.Add(new Contact(userId, contactsToAdd.get(i))); 
} 

for (Contact contact in contacts) 
{ 
    Session.Save(contact); 
} 
관련 문제