有人通过 Hibernate 将 PostgreSQL 中的数值数组映射到 Java 中的 CustomObject 列表吗?
SQL
CREATE TABLE sal_emp (name varchar, work_station bigint[]);
INSERT INTO sal_emp VALUES ('one', '{1,2}');
INSERT INTO sal_emp VALUES ('two', '{3,4}');
INSERT INTO sal_emp VALUES ('three', '{2,4}');
CREATE TABLE station(station_id bigint, station_name varchar, station_timezone varchar);
INSERT INTO station values (1, 'ABC', 'Sample Time');
INSERT INTO station values (2, 'DEF', 'Sample Time');
INSERT INTO station values (3, 'GHI', 'Sample Time');
INSERT INTO station values (4, 'JKL', 'Sample Time');
班级
public class SalEmp implements Serializable{
private String name;
private List<Station> stations;
...// getters & setters
}
public class Station implements Serializable{
private Long stationId;
private String stationName;
private String stationTimezone;
...// getters & setters
}
我检查了这篇post中的答案,它没有讨论自定义对象。我不确定这是否可能或数据库设计本身是错误的!
您可以在 sal_emp 和 station 之间创建一个表。您可以像这样为其创建 JPA 实体:
@Entity
@Table(name = "sal_emp_station")
class SalEmpStation {
@Id
Long id;
@ManyToOne
@JoinColumn(name = "sal_emp_id")
SalEmp salEmp;
@ManyToOne
@JoinColumn(name = "station_id")
Station station;
// additional properties
// standard constructors, getters, and setters
}
然后配置 SalEmp 和 Station 类中的关系。 SalEmp 和 Station 实体是双向的。
class SalEmp {
// ...
@OneToMany(mappedBy = "salEmp", cascade = CascadeType.ALL, orphanRemoval = true)
Set<SalEmpStation> salEmpStations;
// ...
}
class Station {
// ...
@OneToMany(mappedBy = "station", cascade = CascadeType.ALL, orphanRemoval = true)
Set<SalEmpStation> salEmpStations;
// ...
}
双向关联在查询中很容易使用。