Spring Boot,Hibernate / JPA和MySQL。我有下表:
multResult
我希望此表能够将O / R映射到具有 CREATE TABLE IF NOT EXISTS fizzbuzzes (
fizzbuzz_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
fizzbuzz_type_a VARCHAR(250) NOT NULL,
fizzbuzz_type_b VARCHAR(250) NOT NULL,
fizzbuzz_type_c VARCHAR(250) NOT NULL,
fizzbuzz_type_d VARCHAR(250) NOT NULL,
fizzbuzz_type_e VARCHAR(250) NOT NULL,
fizzbuzz_type_f VARCHAR(250) NOT NULL,
fizzbuzz_type_g VARCHAR(250) NOT NULL,
fizzbuzz_type_h VARCHAR(250) NOT NULL,
fizzbuzz_type_i VARCHAR(250) NOT NULL,
fizzbuzz_type_j VARCHAR(250) NOT NULL,
fizzbuzz_type_k VARCHAR(250) NOT NULL,
fizzbuzz_type_l VARCHAR(250) NOT NULL,
fizzbuzz_type_m VARCHAR(250) NOT NULL,
fizzbuzz_type_n VARCHAR(250) NOT NULL,
fizzbuzz_type_o VARCHAR(250) NOT NULL,
fizzbuzz_type_p VARCHAR(250) NOT NULL,
CONSTRAINT pk_fizzbuzzes PRIMARY KEY (fizzbuzz_id);
);
的JPA实体,该实体包含所有fizzbuzz类型A到P.
所以不是你通常会看到的:
Map<String,String>
...相反,我想:
@Entity
@Table(name = "fizzbuzzes")
public class Fizzbuzz {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "fizzbuzz_type_a")
private String typeA;
@Column(name = "fizzbuzz_type_a")
private String typeB;
// ...
@Column(name = "fizzbuzz_type_a")
private String typeP;
// Getters, setters & ctors
}
@Entity
@Table(name = "fizzbuzzes")
public class Fizzbuzz {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "???")
private Map<String,String> types;
// Getters, setters & ctors
}
的密钥可能是硬编码字符串types
,typeA
,...,typeB
,typeP
的值将是值来自DB表中的各个列。
这可能吗,如果是这样的话?
答案 0 :(得分:3)
排序。如果您可以将类型值放在单独的表中,则可以。然后,您可以使用@ElmentCollection
和@MapKeyColumn
。
例如:
@ElementCollection
@MapKeyColumn(name="type_key")
@Column(name="type_value")
@CollectionTable(name="fizzbuzz_types", joinColumns=@JoinColumn(name="fizzbuzz_id"))
Map<String, String> types= new HashMap<>();
否则,需要为您的第一样品中有硬编码类型的列,并可以添加@PostLoad
和@PrePersist
钩从瞬态地图静态列转换为/
类似的东西:
@Entity
@Table(name = "fizzbuzzes")
public class Fizzbuzz {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "fizzbuzz_type_a")
private String typeA;
@Column(name = "fizzbuzz_type_a")
private String typeB;
@Transient
private Map<String, String> types = new HashMap<>();
@PostLoad
public void toMap() {
this.types.put("typeA", this.typeA);
this.types.put("typeB", this.typeB);
}
@PrePersist
public void fromMap() {
this.typeA = this.types.get("typeA");
this.typeB= this.types.get("typeB");
}
}