質問

I am using sql server 2008R2 for my java enterprise app. Now, I want that while persisting a bean its Id column gets automatically updated. My entity bean is:

@Entity
@Table(name = "BANK_MASTER")
@XmlRootElement
public class BankMaster implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id    
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Basic(optional = false)
    @NotNull
    @Column(name = "BANK_ID")
    private Long bankId;

    @Size(max = 30)
    @Column(name = "BANK_NAME")
    private String bankName;

    @Size(max = 25)
    @Column(name = "IP_ADDRESS")
    private String ipAddress;

    @Size(max = 255)
    @Column(name = "URL")
    private String url;

    @Size(max = 1)
    @Column(name = "FORM_METHOD")
    private String formMethod;

    @Size(max = 1)
    @Column(name = "SECURED")
    private String secured;

    @Column(name = "ACTIVEFLAG")
    private Short activeflag;

    @Column(name = "ENABLED")
    private Short enabled;

    @OneToMany(mappedBy = "bankId")
    private Collection<BankBranchMaster> bankBranchMasterCollection;

    @JoinColumn(name = "PARTNER_ID", referencedColumnName = "UA_ID")
    @ManyToOne
    private PartnerAccount partnerId;
}

However when I persist the bean it gives constraint error. My table create query is as follows:

    CREATE TABLE [dbo].[BANK_MASTER](
[BANK_ID] [numeric](10, 0) IDENTITY(105,1) NOT NULL,
[BANK_NAME] [varchar](30) NULL,
[IP_ADDRESS] [varchar](25) NULL,
[URL] [varchar](255) NULL,
[FORM_METHOD] [varchar](1) NULL,
[SECURED] [varchar](1) NULL,
[PARTNER_ID] [numeric](10, 0) NULL,
[ACTIVEFLAG] [numeric](1, 0) NULL,
[ENABLED] [numeric](1, 0) NULL
役に立ちましたか?

解決

You've added @NotNull to the id property. This thus means that JPA will check that this id is not null before persisting. But the id is null, since it will be generated after, by the database. So, the NotNull annotation is in direct contradiction with the fact that it's auto-generated by identity.

Simply remove the @NotNull annotation from id.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top