Search code examples
javahibernatehibernate-annotations

How can I access the mapping field directly whilst also having a relationship defined


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


    private int cityDestinationId;

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

I have this relationship, where I can get the cities easy by the mapping defined, but I also need to be able to set and alter the cityDestinationId directly because it's supplied to me by external source.

What annotations do I need to be able to do that without losing any functionality(getting cities as object, being able to set/alter/get id from the field/getters/setters)

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'modelDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory nl.exit.crunch.dao.AbstractDao.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [nl/exit/crunch/config/HibernateConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: nl.exit.crunch.table.some.destination.CityLocation column: cityDestinationId (should be mapped with insert="false" update="false")


Solution

  • 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