zoukankan      html  css  js  c++  java
  • @OneToMany 一对多 通过表之间的链接

    https://blog.csdn.net/qq_38157516/article/details/80146547

    一对多

    一个人对多张卡,但是一张卡只能对应一个人,典型的一对多关系,下面就用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就不用创建中间表
    ————————————————
    版权声明:本文为CSDN博主「穷水叮咚」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_38157516/article/details/80146547

  • 相关阅读:
    防火墙实践
    提高工作效率的小技巧
    网络系统参数配置
    linux 文件截取
    python (1) 还不是大全的小问题
    iptables 命令记录
    网络常用端口
    HTTP时间指标
    错误集锦
    access数据库调用
  • 原文地址:https://www.cnblogs.com/xiayule/p/jpa123.html
Copyright © 2011-2022 走看看