Spring Data JPA 多对多表查询
Posted viewts
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Data JPA 多对多表查询相关的知识,希望对你有一定的参考价值。
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<Card> 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<Goods> 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<Goods, Long> { }
package com.wts.bloodline.repository; import com.wts.bloodline.entity.Card; import org.springframework.data.jpa.repository.JpaRepository; public interface CardRepository extends JpaRepository<Card, Long> { }
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 多对多表查询的主要内容,如果未能解决你的问题,请参考以下文章