JPA的可嵌入类中可以包含对象引用吗?

huangapple go评论72阅读模式
英文:

Can JPA Embeddable class contain an object reference?

问题

我正在尝试将一个包含对象引用的类嵌入到另一个类中。我总是会得到以下异常:
org.hibernate.MappingException: 无法确定类型:...
我的问题是,是否有任何方法可以嵌入一个包含对象引用的类,或者可嵌入的类只能存储原始数据类型。

我已经尝试过使用@Target()注解,但没有帮助。

英文:

I'm trying to embed a class to another which contains object reference. I always get

org.hibernate.MappingException: Could not determine type for: ...

exception. My question is there any way I can embed a class which contains object references, or embeddable classes only stores primitives.

I'm already tried @Target() annotation but not helps.

答案1

得分: 2

是的,这是可能的。查看文档

@Embeddable
public static class Publisher {

	private String name;

	@ManyToOne(fetch = FetchType.LAZY)
	private Country country;

	//Getters and setters, equals and hashCode methods omitted for brevity
}

@Entity(name = "Book")
@AttributeOverrides({
	@AttributeOverride(
		name = "ebookPublisher.name",
		column = @Column(name = "ebook_publisher_name")
	),
	@AttributeOverride(
		name = "paperBackPublisher.name",
		column = @Column(name = "paper_back_publisher_name")
	)
})
@AssociationOverrides({
	@AssociationOverride(
		name = "ebookPublisher.country",
		joinColumns = @JoinColumn(name = "ebook_publisher_country_id")
	),
	@AssociationOverride(
		name = "paperBackPublisher.country",
		joinColumns = @JoinColumn(name = "paper_back_publisher_country_id")
	)
})
public static class Book {

	@Id
	@GeneratedValue
	private Long id;

	private Publisher ebookPublisher;

	private Publisher paperBackPublisher;

	//Getters and setters are omitted for brevity
}
英文:

Yes, this is possible. Look at the documentation.

@Embeddable
public static class Publisher {

	private String name;

	@ManyToOne(fetch = FetchType.LAZY)
	private Country country;

	//Getters and setters, equals and hashCode methods omitted for brevity
}


@Entity(name = "Book")
@AttributeOverrides({
	@AttributeOverride(
		name = "ebookPublisher.name",
		column = @Column(name = "ebook_publisher_name")
	),
	@AttributeOverride(
		name = "paperBackPublisher.name",
		column = @Column(name = "paper_back_publisher_name")
	)
})
@AssociationOverrides({
	@AssociationOverride(
		name = "ebookPublisher.country",
		joinColumns = @JoinColumn(name = "ebook_publisher_country_id")
	),
	@AssociationOverride(
		name = "paperBackPublisher.country",
		joinColumns = @JoinColumn(name = "paper_back_publisher_country_id")
	)
})
public static class Book {

	@Id
	@GeneratedValue
	private Long id;

	private Publisher ebookPublisher;

	private Publisher paperBackPublisher;

	//Getters and setters are omitted for brevity
}

huangapple
  • 本文由 发表于 2020年8月22日 19:34:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63535685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定