如何使用Hibernate / JPA从另一个表中从另一个表中检索一列
我想使用外键“ model_id
”仅检索一个列“ model_name
”从tt_cars表中, 我尝试了以下代码,但它返回了整个汽车对象。
@JoinColumn(name = "MODEL_ID", referencedColumnName = "ID")
@ManyToOne(fetch = FetchType.EAGER)
private CARS cars;
另外,我尝试了下面的代码,它也无法正常工作
@SecondaryTable(name = "TT_CARS", pkJoinColumns = @PrimaryKeyJoinColumn(name = "ID", referencedColumnName="MODEL_ID"))
,还有其他方法可以使用Hibernate和JPA保留列(model_name
)?
备注:模型名称应为选项
类的一部分。
我的代码
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name = "TT_OPTIONS")
public class Options {
@Id
@Column(name = "ID")
private String id;
@NotNull
@Column(name = "DESCRIPTION", nullable = false)
private String description;
@Column(name = "MODEL_ID") // Foreign key
private Long modelId;
@Column(name = "MODEL_NAME", table = "TT_CARS") // this is the column name I would like to retrieve from the TT_CARS table
private String modelName;
// getters and setters
}
I would like to use the Foreign key "MODEL_ID
" to retrieve just one column "MODEL_NAME
" from the TT_CARS table,
I tried the following code, that works but it returns the whole CARS object.
@JoinColumn(name = "MODEL_ID", referencedColumnName = "ID")
@ManyToOne(fetch = FetchType.EAGER)
private CARS cars;
Also I tried the code below, its also not working
@SecondaryTable(name = "TT_CARS", pkJoinColumns = @PrimaryKeyJoinColumn(name = "ID", referencedColumnName="MODEL_ID"))
Is there other way to retieve just the column (MODEL_NAME
) using hibernate and JPA??
remarks: The modelName should be part of the Options
class.
my code
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name = "TT_OPTIONS")
public class Options {
@Id
@Column(name = "ID")
private String id;
@NotNull
@Column(name = "DESCRIPTION", nullable = false)
private String description;
@Column(name = "MODEL_ID") // Foreign key
private Long modelId;
@Column(name = "MODEL_NAME", table = "TT_CARS") // this is the column name I would like to retrieve from the TT_CARS table
private String modelName;
// getters and setters
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用@noreflow noreferrer“>@formula 。它是仅读取的列,可以通过自定义子查询检索。它不存在于目标表中。
示例:
Hibernate生成的本机查询:
You can use @Formula. It is read-only calculated column that can be retrieved by the custom subquery. It does not present in the target table.
Example:
Hibernate generated native query:
@SecondaryTable designed for @OneToOne relationship to map multiple tables to the same entity. It will not work for the @ManyToOne relationship.