在這個系統中,我們會需要儲存許多資料欄位。
在 Java 的 Spring 框架中,Entity 是用來映射資料庫資料表的類別。每個 Entity 通常對應到一個資料表,類別中的屬性則對應到資料表的欄位。每個 FavoriteDrink
Entity 代表這個飲料系統中該使用者的收藏飲品項目,負責儲存每一杯飲品的相關資訊,像是使用者(user)、飲品名稱(drinkName)、飲品分類(drinkCategory)、飲品描述(drinkDescription)、價格(price)、標籤(tags)、個人備註(notes)、建立時間(createdAt)等等 ······
通常也會使用JPA (Java Persistence API) 的註解來標示,例如 @Entity 表示這是一個資料表對應的類別,@Table 可以指定資料表名稱,@Id 標示主鍵欄位,@GeneratedValue 用於主鍵自動生成。每個欄位會用 @Column 註解來對應資料表的欄位名稱與型態。例如:
@Entity
@Table(name = "favorite_drinks")
public class FavoriteDrink {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "drink_name", nullable = false)
private String drinkName;
@Column(name = "drink_category")
private String drinkCategory;
@Column(name = "drink_description", columnDefinition = "TEXT")
private String drinkDescription;
@Column(name = "price")
private Double price;
@Column(name = "tags", columnDefinition = "TEXT")
private String tags; // JSON format for tags
@Column(name = "notes", columnDefinition = "TEXT")
private String notes; // User's personal notes
@Column(name = "created_at")
private LocalDateTime createdAt;
這些欄位能完整記錄使用者對飲品的偏好與個人化資訊,方便後續查詢、推薦或串接 AI Agent 進行分析,也可以直接操作 FavoriteDrink
物件,並透過 ORM(物件關聯對映)自動將資料同步到資料庫。好處是程式碼結構清晰、易於維護,且能減少 SQL 操作的複雜度。透過 Entity,開發者能以物件導向方式管理資料,提升開發效率與資料一致性。
而在 FavoriteDrink
的 Constructors 包含一帶有 name、category、description、price 四個參數的建構子,方便建立物件時初始化主要欄位。
// Constructors
public MenuItem() {}
public MenuItem(String name, String category, String description, Double price) {
this.name = name;
this.category = category;
this.description = description;
this.price = price;
}
Getter/Setter 方法讓外部程式安全地存取和修改物件屬性,是 Java Bean 標準寫法,方便 Spring Data JPA 進行資料庫操作。
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }
}
如此一來,AI Agent 就可以根據 FavoriteDrink
的資料,分析使用者偏好,進行個人化的推薦,並依據 tags
、notes
等欄位,理解使用者的口味、需求,在聊天室的對話中給出更貼合的建議。
參考資料: