我有一个表,为了持久性,我必须用JPA注释编写类。表格是这样的:
CGRect
我尝试了这个,但是我认为它是不完整的。缺少什么了吗?我写的对吗?
CREATE TABLE `team` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `player` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`team_id` int(11) unsigned NOT NULL,
`name` varchar(16536) NOT NULL,
`position` varchar(16536) NOT NULL,
PRIMARY KEY (`id`),
KEY `team_id` (`team_id`),
CONSTRAINT `player_ibfk_1` FOREIGN KEY (`team_id`) REFERENCES `team` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
答案 0 :(得分:0)
JPA将按其类别映射外国实体。
尝试以下操作:
@Entity
public class Team {
@Id @GeneratedValue long id;
private String name;
}
@Entity
public class Player {
@Id @GeneratedValue long id;
Team teamId;
String name;
String position;
}
答案 1 :(得分:0)
团队有更多玩家。这是1:N关系。在JPA中,您可以使用App Center Push注释创建它:
@Entity
@Table("team")
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Column(nullable = false)
String name;
@OneToMany(mappedBy = "team", cascade = CascadeType.ALL)
List<Player> players = new ArrayList<>();
}
@Entity
@Table("player")
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne(fetch=FetchType.LAZY, optional = false)
@JoinColumn("team_id")
Team team;
@Column(nullable = false)
String name;
@Column(nullable = false)
String position;
}
对于id,请使用对象类型Long。在持续时间,实体ID为null。持久后,DB将为其分配值。