我正在尝试使用Hibernate在User表和Message表之间创建一对多的关系。一个用户可以在消息数据库中拥有多条消息。但是,我无法获得它的架构。 这是我的代码
User.java
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
User user;
@Column(unique = true)
private String username;
private String password;
@OneToMany
Message message;
public User(String userName, String password) {
this.username = userName;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Message.java
@Entity
public class Message {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String sender;
private String receiver;
private String content;
@Type(type="timestamp")
private Date created;
public Message() {
}
public Message(String sender, String receiver, String content) {
this.sender = sender;
this.receiver = receiver;
this.content = content;
this.created = new Date();
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
这是我的架构
CREATE TABLE `Message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` varchar(255) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`receiver` varchar(255) DEFAULT NULL,
`sender` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `User` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`password` varchar(255) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_jreodf78a7pl5qidfh43axdfb` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
但不幸的是,我无法获得用户和消息的一对多关系。任何人都可以帮我做。如何设计模式以获得一对多关系以及如何更改POJO类以实现它?
答案 0 :(得分:1)
您正在以错误的方式实施OneToMany
关系,您应该在Collection
实体中使用User
条消息
@OneToMany
private List<Messages> messages; // Or Set<>
答案 1 :(得分:0)
尝试在指向用户的邮件类中放置ManyToOne装饰器。
@ManyToOne
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
private User user;
从用户
中删除@OneToMany