我有一个数据库表,其中主键定义为时间戳。应用程序根据触发的特定事件将记录插入数据库,使用的时间戳将是创建此实例的时间戳。由于此应用程序在多个服务器上运行,并且该事件同时在多个服务器中同时触发,因此在某些情况下,由于违反主键,数据不会插入到数据库中。
为了避免这种情况,我可以做些什么改变?我目前的想法是,
在执行数据库插入之前等待一个随机时间。
Random r = new Random(); long time = r.nextLong() % 1000; time = time < 0 ? -time : time; // making sure that the waiting time is positive try { Thread.sleep(time); } catch (InterruptedException e) { throw new CustomeException(e); } Table1DataAccess.getInstance().insert(new Date(), "some description"); // inserting data into the table which has two fields.
使主键成为复合键。
它们对我来说都不是很好的解决方案,谁能给我指出正确的方向?
附言我尝试向其中插入数据的表的时间戳列为 Date
类型,我猜它的精度只有几秒。当我改为使用 timestamp
类型时,它提供了默认的微秒精度,并且最多可以提供纳秒。
最佳答案
不要使用时间戳作为主键字段。
对主键自增字段使用 Integer 或 BigInt
关于java - 使用时间戳作为主键时避免违反主键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39997970/