JPA 使用@OneToMany
程序员文章站
2022-04-22 21:56:02
...
一对多
一个人对多张卡,但是一张卡只能对应一个人,典型的一对多关系,下面就用OneToMany来自动生成sql语句
首先建表s_person和s_card表
s_card表
然后在创建一张表关联两张表的关系s_person_card,P_ID为s_person的id,C_ID为s_card的id
建Person.java实体类
@Entity
@Table(name="s_person")
public class Person {
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Id
private String id;
private String username;
private String age;
//JoinTable的name是中间表的名字
@OneToMany(fetch=FetchType.EAGER)
@JoinTable(name="s_person_card",joinColumns={@JoinColumn(name="p_id")}
,inverseJoinColumns={@JoinColumn(name="c_id")})
private List<Cards> cards;
public List<Cards> getCards() {
return cards;
}
public void setCards(List<Cards> cards) {
this.cards = cards;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
然后是cards表
@Entity
@Table(name="s_card")
public class Cards {
private String id;
private String num;
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
新建接口
public interface PersonRepository extends JpaRepository<Person, String>{
Person findById(String id);
}
测试
@RequestMapping("/person")
@ResponseBody
public Person person(){
Person person=personRepository.findById("12323423");
List<Cards> cards = person.getCards();
for (Cards card : cards) {
System.out.println(card.getId());
System.out.println(card.getNum());
}
return person;
}
结果正常打印,发了两条sql语句,没有手动写sql
只是测试的onetomany,有点复杂,如果在cards类中添加用manytoone就不用创建中间表