开发者

Problem with id column and JPA

I'm trying JPA with a very simple class for the Play! framework and I'm having some problems with the id column.

My sql database has only two columns:

CREATE TABLE IF NOT EXISTS `开发者_如何学Goauto` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

And my model is:

@Entity
@Table(name = "auto")
public class Auto extends Model{

    @Column(insertable = false, updatable = false)
    public int id;

    public String name;

    public Auto(String name){
        this.name = name;
    }
}

Everything works fine without this part:

    @Column(insertable = false, updatable = false)
    public int id;

As soon as I add public int id; I'd get this error though: A JPA error occurred (Unable to build EntityManagerFactory): Repeated column in mapping for entity: models.Auto column: id (should be mapped with insert="false" update="false")

And that's the reason I've added the column annotation, but it doesn't work with that neither, now I'm getting:

A javax.persistence.PersistenceException has been caught, org.hibernate.PropertyAccessException: could not set a field value by reflection setter of models.Auto.id

I'm testing the model this way: new Auto("bmw").save(); save() is a method from the model class in the playframework.

Anyone know why I'm having this problem? Thanks!


Hmm, try it completely without the id field. Looks like Playframework auto-creates an Id field if extending the Model class. See here:

"... If you have used JPA before, you know that every JPA entity must provide an @Id property. Here the Model superclass provides an automatically generated numeric ID, and in most cases this is good enough. ..."


class Model already adds an id field, of type Long. This is conflicting with the id field you add on your class definition.

Just remove the id field from Auto and it should work. I'm not sure if the definition of int(11) in your database is correct, but JPA should automatically solve that if required.


Should't the column be annotated similar to following ?

@Id
@GeneratedValue(generator="???_seq",strategy=GenerationType.SEQUENCE)


The problem you are having relates to underestimating what you are getting for ´free´ in the play framework.

Both the ID (your original question) and the getters and setters (your follow up comment) are generated automatically for you.

The id field comes from the Model class, which you are extending, and the getters and setters are automatically generated and used when you make a public field in your model, and then refer to it later as model.field.

While all models will have an Id provided for them, it is recommended to use your own custom IDs if they are to do anything more complex or meaningful.


If you need to add your own id field (for example, because it needs to be an Integer rather than a Long), you can extend GenericModel rather than Model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜