简体   繁体   English

Java servlet使用复合键将数据插入mysql db

[英]java servlet inserting data into mysql db with composite key

I'm working on a servlet that needs to insert some data to the db table with a composite primary key consists of the userid, dataid and CURRENT_TIMESTAMP . 我正在使用一个servlet,它需要使用由userid,dataid和CURRENT_TIMESTAMP组成的复合主键将一些数据插入db表。 however im getting the following error when executing the query 但是我在执行查询时收到以下错误

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry'13-7-2013-09-13 23:22:24' for key 'PRIMARY'

I think this is caused by the multiple insertion of rows to the same table in the same time, though with different dataid. 我认为这是由于在同一时间多次将行插入同一张表而导致的,尽管使用了不同的dataid。 Is there any solution to this problem? 有什么解决办法吗? Should I cancel CURRENT_TIMESTAMP as a part of the primary key to do the trick or there are some other better workarounds? 我是否应该取消CURRENT_TIMESTAMP作为主键的一部分来进行操作,还是应该有其他更好的解决方法?

Thanks a lot and appreciate for any help! 非常感谢,并感谢您的帮助!

If it's a log table , it is recommended not to use a primary key. 如果是日志表 ,建议不要使用主键。 If you want to accelerate some search in this table, create the appropriate indexes. 如果要加快此表中的搜索速度,请创建适当的索引。

If you need a primary key (for example, if you plan to use it with JPA), it would be best to use a number, eg 如果您需要主键(例如,如果您计划将其与JPA一起使用),则最好使用数字,例如

ID int AUTO_INCREMENT PRIMARY KEY

For example, log4j can insert each event log into a database using a org.apache.log4j.jdbc.JDBCAppender . 例如,log4j可以使用org.apache.log4j.jdbc.JDBCAppender将每个事件日志插入数据库。

See also MySQL storage engine for a large log table . 有关大型日志表,另请参见MySQL存储引擎

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM