我正在尝试使用Spring JPA(Hibernate)映射现有数据库表。例如,一个表(THING)具有包含另一个表(PLACE)的外键的复合主键。我试图通过为Thing创建一个单独的IdClass来映射这个,但是当我尝试通过Can not set cktest.Place field cktest.ThingId.place to java.lang.Long
save
Thing
CrudRepository<Thing, ThingId>
时我得到@Entity
public class Place {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "ID")
private long id;
@Column(name = "NAME", nullable = false)
private String name;
@OneToMany(mappedBy = "place")
Set<Thing> things;
... constructor, get/set methods, equals, hashCode ...
}
我的地图不正确,还是这是JPA限制?有解决办法吗?
Place.java:
@Entity
@IdClass(ThingId.class)
public class Thing {
@Id
String name;
@Id
Place place;
... constructors, get/set methods, equals, hashCode ...
}
Thing.java:
@Embeddable
public class ThingId implements Serializable {
@ManyToOne
@JoinColumn(name = "PLACE_ID", referencedColumnName = "ID", nullable = false)
private Place place;
@Column(name="NAME")
private String name;
}
ThingId.java:
... imports ...
public interface ThingRepository extends CrudRepository<Thing, ThingId> {}
ThingRepository.java:
@Configuration
@EnableAutoConfiguration
public class Main {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Main.class);
PlaceRepository placeRepository = context.getBean(PlaceRepository.class);
ThingRepository thingRepository = context.getBean(ThingRepository.class);
// save a place
Place home = placeRepository.save(new Place("Home"));
// save a thing
Thing re = new Thing(home, "Fido");
// Throws
thingRepository.save(re);
context.close();
}
}
Main.java:
{{1}}