mysql - 多对多关系 - 在 MySQL 中获取双行

标签 mysql json spring hibernate spring-boot

就像标题所说,我的项目中存在多对多关系,当客户可以拥有许多优惠券时,反之亦然。为了做到这一点,我在 MySQL 中创建了另一个表,其中包括优惠券 ID 和客户 ID(每行),但不知何故,每次我向客户添加优惠券时,它都会将 coupon_customer 表中的行加倍。 例如:

优惠券-> ID 1

客户->id 4

first add

现在我向同一客户添加另一张优惠券(id 2),这就是结果:

second add

我的代码:

客户:

@Entity
@Table(name = "customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "password")
    private String password;

    @ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH,
            CascadeType.REFRESH })
    @JoinTable(name = "coupon_customer", joinColumns = @JoinColumn(name = "customer_id"), inverseJoinColumns = @JoinColumn(name = "coupon_id"))
    private List<Coupon> coupons;

    public Customer() {
    }

    public Customer(String name, String password) {

        this.name = name;
        this.password = password;
        this.coupons = new ArrayList<Coupon>();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @JsonIgnore
    public List<Coupon> getCoupons() {

        return coupons;
    }

    public void setCoupons(ArrayList<Coupon> coupons) {
        this.coupons = coupons;
    }

    @Override
    public String toString() {
        return "Customer [id=" + id + ", name=" + name + ", password=" + password + "]";
    }

}

优惠券:

@Entity
@Table(name = "coupon")
public class Coupon {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "start_date")
    private Date startDate;

    @Column(name = "end_date")
    private Date endDate;

    @Column(name = "amount")
    private int amount;

    @Enumerated(EnumType.STRING)
    @Column(name = "type")
    private CouponType type;

    @Column(name = "message")
    private String message;

    @Column(name = "price")
    private double price;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id")
    private Company company;

    @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH,
            CascadeType.REFRESH })
    @JoinTable(name = "coupon_customer", joinColumns = @JoinColumn(name = "coupon_id"), inverseJoinColumns = @JoinColumn(name = "customer_id"))
    private List<Customer> customers;

    public Coupon() {
    }

    public Coupon(String title, Date startDate, Date endDate, int amount, CouponType type, String message,
            double price) {

        this.title = title;
        this.startDate = startDate;
        this.endDate = endDate;
        this.amount = amount;
        this.type = type;
        this.message = message;
        this.price = price;

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public CouponType getType() {
        return type;
    }

    public void setType(CouponType type) {
        this.type = type;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @JsonIgnore
    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    @JsonIgnore
    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }

    @Override
    public String toString() {
        return "Coupon [id=" + id + ", title=" + title + ", startDate=" + startDate + ", endDate=" + endDate
                + ", amount=" + amount + ", type=" + type + ", message=" + message + ", price=" + price + "]";
    }

客户 Controller :

@RequestMapping(value = "/purchaseCoupon")
    public ResponseEntity<CouponSystemResponse> purchaseCoupon(@RequestParam(value = "id") int id) {
        try {

            Coupon coupon = couponService.getCoupon(id);
            getEntity().getCoupons().add(coupon); --> getEntity() gets the customer 
            coupon.setAmount(coupon.getAmount() - 1);
            customerService.updateCustomer(getEntity()); --> updates customer after purchase coupon
            couponService.updateCoupon(coupon); --> update coupon after been purchased(amount -1)

.....

如果这对 MySQL 脚本有帮助:

DROP SCHEMA IF EXISTS `couponsystem`;

CREATE SCHEMA `couponsystem`;

use `couponsystem`;



DROP TABLE IF EXISTS `company`;

CREATE TABLE `company` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL UNIQUE,
  `password` varchar(20) NOT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
);


DROP TABLE IF EXISTS `coupon`;

CREATE TABLE `coupon` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(20) NOT NULL UNIQUE,
  `start_date` datetime DEFAULT NULL,
  `end_date` datetime DEFAULT NULL,
  `amount` int DEFAULT NULL,
  `type` varchar(15) DEFAULT NULL,
  `message` varchar(50) DEFAULT NULL,
  `price` float DEFAULT NULL,
  `company_id` int(11),
  PRIMARY KEY (`id`),
  KEY `FK_company_id` (`company_id`),
  CONSTRAINT `FK_company_id` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
);

DROP TABLE IF EXISTS `customer`;

CREATE TABLE `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL UNIQUE,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);


CREATE TABLE `coupon_customer`(
`coupon_id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
/*
PRIMARY KEY (`coupon_id`,`customer_id`), --> that's in comment only cause I got exception every time row doubles itself and tried looking for solutions
*/
CONSTRAINT `FK_coupon_id` FOREIGN KEY (`coupon_id`) REFERENCES `coupon` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE

);

客户服务:

@Service
public class CustomerService {

    @Autowired
    CustomerRepository customerRepo;


    .....

    public void updateCustomer(Customer customer) {
        customerRepo.save(customer);
    }

   .....

优惠券服务:

@Service
public class CouponService {

    @Autowired
    CouponRepository couponRepo;

    ......
    public void updateCoupon(Coupon coupon) {
        couponRepo.save(coupon);
    }
    ......

奇怪的东西。就像它需要所有最后一行添加它们,然后添加其他行。我以为我有级联,但无法使其工作......感谢任何帮助。

最佳答案

首先,我会向 coupon_customer 表添加另一个约束,这是一个独特的组合,提供 INSERT IGNORE 命令,它将跳过插入错误,它将为此类错误提供基本的数据库保护

ALTER TABLE coupon_customer ADD  UNIQUE KEY coupon_customer (coupon_id, customer_id);

插入应该是:

INSERT IGNORE INTO...

除此之外,生成查询的函数应该为每个键接收一个参数并生成最简单的查询。如果使用 select 构建的插入 js 或该函数在带有数组的函数上运行,那么这些可能会生成您所描述的错误

public function add coupon($customer_id, $coupon_id) {
... 

$sql =  "INSERT IGNORE INTO coupon_customer VALUES (". $customer_id . ",". $coupon_id . ");" ;
... 
} 

关于mysql - 多对多关系 - 在 MySQL 中获取双行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457282/

相关文章:

php - jQuery ajax (JSON) 从 PHP 获取数组工作正常,但在网络服务器上不行

javascript - 使用 HTML 输入 'name' 属性生成对象

json - 找不到案例类的 JsonWriter 或 JsonFormat 类型类

java - 使用 Spring Boot 和 Thymeleaf 发送 HTML 电子邮件

java - 基于运行时提供的字符串查找要使用哪个接口(interface)实现的优雅解决方案

Mysql 5.7 json 列无法按预期工作

sql - select * from table where datetime in month(不破坏索引)

java - 无法加载资源 : the server responded with a status of 404 ()

具有唯一索引的 SQL 克隆记录

php - 我收到类似未捕获异常 'PDOException' 的错误,消息为“SQLSTATE[42000] : Syntax error or access violation: 1064”