开发者

Hibernate Annotations - id is not set correctly

I have a whole bunch of Java beans annotated like this with JPA:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class TitleEntry extends Entry {
    private Long id;

    public TitleEntry() { }

    public TitleEntry(String code, String label) {
        super(code, label);
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    protected void setId(Long id) {
        this.id = id;
    }
}

The id is always genera开发者_如何学Goted like this for every object and seems to be working fine.

Now the problem: When I save an object in Java:

dao.save(titleEntry);

the id-property of the bean is set to a int-value, that does not correspond with the actual id. It corresponds to the hibernate_sequence (I think).

Questions:

  1. Why?
  2. What is hibernate_sequence anyway (can't find a decent explanation on Hibernate website)?
  3. How can I fix it?

Note: I'm using Java 1.6, MSSQL2005, Hibernate3


Why?

I don't know, the previous paragraph about some "actual id" doesn't make any sense. Can you clarify? Showing the structure of your TitleEntry table might also help.

What is hibernate_sequence anyway (can't find a decent explanation on Hibernate website)?

The default name of a sequence or table used by Hibernate (see 5.1.5. Enhanced identifier generators). Given than SQL Server doesn't support sequence, I'd bet on the later. You should check the generated DDL to find what has been done exactly (and show the relevant part).

But I'm surprised that Hibernate didn't default to IDENTITY (what version of Hibernate are you using exactly?).

How can I fix it?

I don't know what you want to fix but if you want full control, don't use an AUTO strategy (IDENTITY is usual with SQL Server).


Try to specify the SequenceGenerator using the corresponding annotation:

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
@SequenceGenerator(name = "myGen", sequenceName = "MY_SEQUENCE")
public Long getId() 
{
    return id;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜