Domanda

Is it possible to avoid setter for primary key with Hibernate XML mapping configuration? When annotations are used you don't have to have setter method declared. See example. I'm using Hibernate version 4.1.2.

  1. XML based configuration

    public class Entity {
        private Integer id;
    
        public Integer getId() {
            return id;
        }
    }
    
    <class name="Language" table="language">
        <id name="id" column="id">
            <generator class="native" />
        </id>
    </class>
    

    While initializing Hibernate exception is thrown

    Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property id in class net.kreuzman.eshop.core.domain.l10n.Language
        at org.hibernate.property.BasicPropertyAccessor.createSetter(BasicPropertyAccessor.java:252)
        at org.hibernate.property.BasicPropertyAccessor.getSetter(BasicPropertyAccessor.java:245)
        at org.hibernate.mapping.Property.getSetter(Property.java:325)
        at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertySetter(PojoEntityTuplizer.java:444)
        at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:182)
        at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82)
    ... 49 more
    
  2. Annotation based configuration

    @Entity
    @Table(name="entity")
    public class Entity {
        @Id
        @Column(name="id")
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Integer id;
    
            public Integer getId() {
                 return id;
            }
    }
    

This works well.

È stato utile?

Soluzione

You can set the access type to field, which will achieve the same thing as putting the annotation on the field.

<class name="Language" table="language">
    <id name="id" column="id" access="field">
        <generator class="native" />
    </id>
</class>

Altri suggerimenti

I think hibernate creates objects via reflection (Class.newInstance()) which is why it need the no args constructor. That way - i don't see how its possible to leave out a setter for a used property. U can mark unused fields as @Transient but thats it.

@GeneratedValue(strategy = GenerationType.IDENTITY)

instead of auto

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top