【问题标题】:Map entity with @SecondaryTable Annotation Spring Hibernate使用 @SecondaryTable 注解 Spring Hibernate 映射实体
【发布时间】:2017-09-20 03:03:09
【问题描述】:

在我的数据库中,我有两个如下所示的表:

CREATE TABLE IF NOT EXISTS `Lokal` (
  `idLokal` int(11) NOT NULL AUTO_INCREMENT,
  `Ocena_idOcena` int(11) NOT NULL,
  PRIMARY KEY (`idLokal`,`Ocena_idOcena`),
  KEY `fk_Lokal_Ocena_idx` (`Ocena_idOcena`)
)


CREATE TABLE IF NOT EXISTS `Ocena` (
  `idOcena` int(11) NOT NULL AUTO_INCREMENT,
  `Ocena` int(1) DEFAULT NULL,
  PRIMARY KEY (`idOcena`)
)

我想使用@SecondaryTable Hibernate 注释将我的Lokal 实体映射到这个Ocena 表,我设法实现的是:

@Entity
@Table(name="Lokal")
@SecondaryTable(name = "Ocena", pkJoinColumns=@PrimaryKeyJoinColumn(name="Ocena_idOcena"))
public class Lokal {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="idLokal")
    private int id; 
    @Column(table="Ocena" ,name="idOcena")
    private int rating;

    //--Getters and Setters skipped--//

}

但我得到的只是一个错误提示:

ERROR: Unknown column 'this_1_.Ocena_idOcena' in 'on clause'

我想我误解了@SecondaryTable 注释,但这是我的第一个 Spring/Hibernate 应用程序,所以我很乐意提供任何帮助。

【问题讨论】:

    标签: java spring hibernate spring-mvc


    【解决方案1】:

    试试这个:

    @Entity
    @Table(name="Lokal")
    @SecondaryTable(name = "Ocena", pkJoinColumns=@PrimaryKeyJoinColumn(name="idOcena"))
    public class Lokal {
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="idLokal")
        private int id; 
        @Column(table="Ocena" ,name="rating")
        private int rating;
    
        //--Getters and Setters skipped--//
    
    }
    

    【讨论】:

    • 我也尝试过这个选项,这给我带来了另一个错误:Repeated column in mapping for entity: com.crud.spring.entity.Lokal column: idOcena (should be mapped with insert="false" update="false")
    • 那是因为rating 的列名与您的主键相同。
    • 我将列的名称更改为 Ocena(评级不起作用,因为我在 Ocena 的表中没有这样的列)没有更多错误,但现在我没有从 DB 收到任何结果,如果我删除 @SecondaryTable注释它工作正常(但不显示 Ocena 表中的列)。
    • 我发现,我没有从 Ocena 的表(nulls)中获取任何数据,即使它映射正确,每个 Lokal 的对象都应该有自己的评级,但在我的视图评级 Clumn 中空。
    • 尝试保存一个新的Lokal 对象,看看辅助表是否正确插入了数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2018-12-10
    • 2014-03-06
    • 2014-04-14
    相关资源
    最近更新 更多