1、建表
# one的一方,种类表
create table t_category
(
id varchar(64) not null
primary key,
name varchar(50) null
)
charset = utf8;
# many的一方, 水果表
create table t_fruit
(
id varchar(64) not null
primary key,
name varchar(50) null,
category_id varchar(64) null,
constraint fk_t_fruit_id
foreign key (category_id) references t_category (id)
)
charset = utf8;
2、实体映射
先映射水果表,知识简单映射
package com.jiang.jpa.otm.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Luosj
* @date 2020/2/16 7:55 PM
*/
@Entity
@Table(name = "t_fruit")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Fruit {
@Id
private String id;
private String name;
}
映射多的一方,这里有点特殊
注意: 如果只是使用@OneToMany这个注释的话, 会出现第三张表, 这个将成为多对多映射关系, 不符合一对多的初衷
解决办法: 添加注释@JoinColumn(name=“category_id”), name的值对应的是fruit表中的外键,也就是字段category_id
package com.jiang.jpa.otm.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;
/**
*
* 水果种类
*
* @author Luosj
* @date 2020/2/16 7:53 PM
*/
@Entity
@Table(name = "t_category")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Category {
@Id
private String id;
private String name;
// 单向一对多: 一个水果类型对应多种水果
@OneToMany(fetch = FetchType.LAZY)
// 必须配置一个外键, 否则会生成一张表,形成多对多关联
@JoinColumn(name = "category_id")
private List<Fruit> fruits = new ArrayList<>();
public Category(String id, String name){
this.id = id;
this.name = name;
}
}
3、数据初始化操作
@Test
public void init(){
// one
Category category = new Category(UUID.randomUUID().toString(), "水果");
// many
Fruit fruit1 = new Fruit(UUID.randomUUID().toString(), "Apple");
Fruit fruit2 = new Fruit(UUID.randomUUID().toString(), "banana");
category.getFruits().add(fruit1);
category.getFruits().add(fruit2);
fruitCategory.save(fruit1);
fruitCategory.save(fruit2);
categoryRepository.save(category);
}