我正在使用play框架构建一个Web应用程序,我遇到了使用这个模式创建数据库模型的问题
**Client** – (many to many) – **Events**
\ /
(one to many) (one to many)
\ /
**COMMENTS**
我可以创建和添加关系
Event event = new Event("Party");
Client client = new Client("test@gmail.com","fname","lname","street","phonenum");
Comment comment = new Comment("test comment!");
//Add relationships
client.addEvent(event);
event.addClient(client);
event.addComment(comment);
comment.addEvent(event);
event.addClient(client);
client.addComment(comment);
但是当我试图坚持数据时
client.save();
event.save();
comment.save();
我收到错误
[error] Test CommentModelTest.testClientEventCommentRelationship failed:
javax.persistence.PersistenceException: org.h2.jdbc.JdbcSQLException: Unique index or primary
key violation: "PRIMARY_KEY_4A ON PUBLIC.EVENT_CLIENT(EVENT_ID, CLIENT_EMAIL)"; SQL statement:
[error] insert into event_client (client_email, event_id) values (?, ?) [23505-172]
课程定义如下所示,如果有人能帮助我解决这个问题,我将非常感激。我是否错误地定义了这种关系?提前谢谢!
客户类:
@Entity
public class Client extends Model {
@Id
public String email;
@Required
public String firstName;
@Required
public String lastName;
public String homeAddress;
public String phoneNumber;
@ManyToMany(mappedBy="clients", cascade=CascadeType.ALL)
public List<Event> events = new ArrayList<Event>();
@OneToMany(mappedBy="client", cascade=CascadeType.ALL)
public List<Comment> comments = new ArrayList<Comment>();
活动类:
@Entity
public class Event extends Model {
@Id
public Long id;
@Required
public String eventName;
@ManyToMany(cascade=CascadeType.ALL)
public List<Client> clients = new ArrayList<Client>();
@OneToMany(mappedBy="event", cascade=CascadeType.ALL)
public List<Comment> comments = new ArrayList<Comment>();
评论类:
@Entity
public class Comment extends Model {
@Id
public Long id;
@Required
public String message;
@ManyToOne(cascade=CascadeType.PERSIST)
public Client client;
@ManyToOne(cascade=CascadeType.PERSIST)
public Event event;
---编辑:-------------------------------
我意识到我哪里出错了。如果您遇到类似的错误,请检查您是否正确使用了模型!在我的JUnit测试中,我尝试将相同的客户端添加到事件两次,导致主键(电子邮件)被复制。
纠正后的关系代码应如下:
client.addEvent(event);
event.addClient(client);
event.addComment(comment);
comment.addEvent(event);
comment.addClient(client);
client.addComment(comment);
答案 0 :(得分:0)
例外情况说你试图两次添加相同的关系。
"PRIMARY_KEY_4A ON PUBLIC.EVENT_CLIENT(EVENT_ID, CLIENT_EMAIL)"
我想这是events
和clients
之间的表格,因此它会映射ManyToMany
关系。
client.addEvent(event);
HERE --> event.addClient(client);
event.addComment(comment);
comment.addEvent(event);
HERE --> event.addClient(client);
client.addComment(comment);
它已添加两次,并且有一个唯一的索引可以阻止它。