如何在定义关系的同时直接访问映射字段

时间:2016-04-25 08:37:33

标签: java hibernate hibernate-annotations

@Entity
@Table(name="sometable_citylocation")
public class CityLocation extends Model implements Serializable {


    private int cityDestinationId;

    @ManyToOne
    @JoinColumn(name="cityDestinationId", referencedColumnName="destinationId")
    private City city;

我有这种关系,我可以通过定义的映射轻松获得城市,但我还需要能够直接设置和更改cityDestinationId,因为它是由外部源提供给我的。

我需要做什么注释才能做到这一点而不会丢失任何功能(将城市作为对象,能够从字段/ getter / setter设置/更改/获取id)

  

线程“main”中的异常   org.springframework.beans.factory.BeanCreationException:错误   创建名为'modelDao'的bean:注入自动装配   依赖失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:private org.hibernate.SessionFactory   nl.exit.crunch.dao.AbstractDao.sessionFactory;嵌套异常是   org.springframework.beans.factory.BeanCreationException:错误   在类路径中定义名为'sessionFactory'的bean   resource [nl / exit / crunch / config / HibernateConfiguration.class]:   调用init方法失败;嵌套异常是   org.hibernate.MappingException:实体映射中的重复列:   nl.exit.crunch.table.some.destination.CityLocation列:   cityDestinationId(应使用insert =“false”进行映射   更新= “假”)

1 个答案:

答案 0 :(得分:0)

The answer is to add insertable and updateable to the object mapping

@JoinColumn(name="cityDestinationId",
            insertable=false, 
            updatable=false, 
            referencedColumnName="destinationId"
        )

Keep in mind that you cannot use the object to bind/unbind relations. This is not relevant in my case since the foreign key will be supplied from external source. All i care about is getting the object out