2

my java code like this:

public class Monitorlog{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;//pk 
    String sn; //  unique constraints(sn,checkpoint)
    String checkpoint;
}

public interface MonitorlogDao extends JpaRepository<Monitorlog, Integer>{}

@Service
public class MonitorlogService{
    @Autowired
    MonitorlogDao monitorlogDao;
    public MonitorlogDao getMonitorlog(){
        return monitorlogDao;
    }
}

The test is like this:

    public void testMonitorlogSerivce(){
        Monitorlog m = new Monitorlog();
        m.setSn("aa");
        m.setCheckpoint("bb");
        monitorlogService.getMonitorlogDao().save(m);
        m = new Monitorlog();
        m.setSn("aa");
        m.setCheckpoint("bb");
        // SQL insert failed here
        try{
            monitorlogService.getMonitorlogDao().save(m);
        }catch(Exception e){
            log("",e);
        }
    }

The secode save(m) is failed , it would like throw a exception, but not. the m.getId() is 0, but no exception catched, why? I use sprint boot ver 2.0.0M. UNIQUE INDEX

CREATE UNIQUE INDEX [IND_IDNO_POSITIONKIND_CHECKPOINT_1] ON 
[dbo].[MONITORLOG] ([CHECKPOINT] DESC, [SN] ASC) 
WITH (IGNORE_DUP_KEY = ON)
drrr
  • 39
  • 6
  • Possible duplicate of [Spring JpaRepositroy.save() does not appear to throw exception on duplicate saves](https://stackoverflow.com/questions/40605834/spring-jparepositroy-save-does-not-appear-to-throw-exception-on-duplicate-save) – asbachb Oct 23 '17 at 10:53
  • Call to save() method should be in transaction for catching exception. – Yogi Oct 23 '17 at 10:56
  • if i make the test like this `m.setId(1)`,and the db has one record what's id is 1.`monitorlogService.getMonitorlogDao().save(m);`will throw the SQLServerException unique-constraints voilated! I guess is the sql jdbc driver problem.I will check it tomorrow. – drrr Oct 23 '17 at 13:03
  • I test it with mssql jdbc 6.2.1.jre8,the same result. – drrr Oct 23 '17 at 13:36
  • it's diffferent from [Spring JpaRepositroy.save() does not appear to throw exception on duplicate saves](https://stackoverflow.com/questions/40605834/spring-jparepositroy-save-does-not-appear-to-throw-exception-on-duplicate-save), that is why voilated by PK,but my problem is voilated by UNIQUE INDEX – drrr Oct 24 '17 at 00:41
  • Hello @drrr, did you ever find a solution? I'm running into the same problem. – John Stoneman May 09 '23 at 09:09

1 Answers1

0

Your provided data on second save violates the PK and/or UK rules of DB.

Always you have to give valid data which will comply the PK and/or UK(unique key) rules to persist in DB for your code.

Zenith
  • 1,037
  • 1
  • 10
  • 21
  • unique-constraint like this : `CREATE UNIQUE INDEX [IND_IDNO_POSITIONKIND_CHECKPOINT_1] ON [dbo].[MONITORLOG] ([CHECKPOINT] DESC, [SN] ASC) WITH (IGNORE_DUP_KEY = ON)` – drrr Oct 23 '17 at 13:39