spring data jpa指定聯合索引


  如何,現在我的表里使用訂單ID和產品ID作為唯一索引,那么需要在定義表實體類時在@Table中指定UniqueConstraint:

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;

/**
 * 產品表
 *
 * @author wulinfeng
 * @since 2019/12/13
 */
@Entity
@Table(name = "t_product", uniqueConstraints = @UniqueConstraint(columnNames = {"orderId", "productId"}))
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ProductItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // 訂單Id
    @Column(nullable = false, length = 32)
    private String orderId;

    // 受理產品編碼
    @Column(length = 32)
    private String productId;

    // 產品名稱
    @Column(length = 32)
    private String productName;

    // 時間戳
    @Column(length = 13)
    private Long timestamp;
}

 

  把原來的t_product表drop掉,重啟spring boot,再看該表,自動加上唯一索引了:

mysql> show index from t_product;
+-----------+------------+-----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table     | Non_unique | Key_name                    | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-----------+------------+-----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| t_product |          0 | PRIMARY                     |            1 | id          | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| t_product |          0 | UK1mvw2lcd07t4cuicl4awfbgkw |            1 | order_id    | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| t_product |          0 | UK1mvw2lcd07t4cuicl4awfbgkw |            2 | product_id  | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
+-----------+------------+-----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
3 rows in set (0.00 sec)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM