Spring Data JPA 多对多表查询

2021-04-30 04:29

阅读:548

标签:ota   关系   注解   car   ble   inverse   vax   drive   format   

1.新建一个Spring Initializr项目,勾选Lombok,Spring Web,Spring Data JPA和MySQL Driver依赖。

这里我的表关系是goods商品表-goods_card-card卡牌表

2.新建实体类Goods.java和Card.java,这里注意不要使用Lombok的@Data注解,改用@Setter和@Getter

package com.wts.bloodline.entity;

import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Entity
@Getter
@Setter
@DynamicInsert
@DynamicUpdate
public class Goods {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Integer district;
    private String channel;
    private BigDecimal price;
    private String username;
    private String password;
    private String remarks;
    private Date createTime;
    private Date updateTime;
    @ManyToMany
    @JoinTable(name = "goods_card",
            joinColumns = {@JoinColumn(name = "goods_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "card_id", referencedColumnName = "id")})
    private List cardList;
}
package com.wts.bloodline.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.List;

@Entity
@Getter
@Setter
public class Card {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String type;
    private String job;
    @ManyToMany
    @JoinTable(name = "goods_card",
            joinColumns = {@JoinColumn(name = "card_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "goods_id", referencedColumnName = "id")})
    private List goodsList;
}

3.创建对应的repository:

package com.wts.bloodline.repository;

import com.wts.bloodline.entity.Goods;
import org.springframework.data.jpa.repository.JpaRepository;

public interface GoodsRepository extends JpaRepository {
}
package com.wts.bloodline.repository;

import com.wts.bloodline.entity.Card;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CardRepository extends JpaRepository {
}

4.修改配置application.yml:

server:
  port: 9090
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/bloodline
    username: root
    password: ‘‘
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true
    open-in-view: true
    properties:
      hibernate:
        format_sql: true
        enable_lazy_load_no_trans: true

5.测试

Spring Data JPA 多对多表查询

标签:ota   关系   注解   car   ble   inverse   vax   drive   format   

原文地址:https://www.cnblogs.com/viewts/p/13230459.html


评论


亲,登录后才可以留言!