在实体中两次使用嵌入式ID类型

时间:2019-01-08 14:58:41

标签: java hibernate spring-boot jpa

在我的spring-boot项目中,我对实体的ID字段有一个自定义类型。我可以在@Embeddable@EmbeddedId的帮助下使用该类型。

但是当我想将另一个具有相同类型的字段添加到单个实体中时,会出现如下所示的列映射异常:

Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: 
com.example.demo.CarEntity column: id (should be mapped with insert="false" update="false")

CarId类:

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Embeddable
public class CarId implements Serializable {
    private String id;

    @Override
    public String toString() {
        return id;
    }
}

CarEntity类:

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Entity
public class CarEntity {

    @EmbeddedId
    private CarId id;

    private String name;

    private CarId anotherId;

}

存储库类:

@Repository
public interface CarRepository extends JpaRepository<CarEntity, CarId> {
}

应用程序类:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(CarRepository repository) {
        return args -> {
            CarId carId = new CarId(UUID.randomUUID().toString());
            String carName = "a car";
            CarEntity carEntity = new CarEntity(carId, carName, carId);
            repository.save(carEntity);
            repository.findAll().forEach(carEntity1 -> {System.out.println(carEntity1.getId());});
        };
    }
}

如何将多个具有相同类型的字段添加到条目类中?

1 个答案:

答案 0 :(得分:0)

我发现的解决方案是按如下方式覆盖anotherId上的字段名称:

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Entity
public class CarEntity {

    @EmbeddedId
    private CarId id;

    private String name;

    @Embedded
    @AttributeOverride(name="id", column = @Column(name = "anotherId"))
    private CarId anotherId;

}