0

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
wannaKnowItAll
  • 340
  • 1
  • 4
  • 20
  • The Exact error is: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist' – Kuldeep S Chauhan Jan 27 '14 at 10:30
  • Identity type is supposed to be used with ms sql... Earlier we had oracle 11g and we successfully used sequence and sequence generator for our auto generation need – Kuldeep S Chauhan Jan 27 '14 at 10:32

1 Answers1

0

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Is there a better way than using Identity generation type. As now using Identity Type I would have to renew all my code where I persist, entering em.flush(), before I could use the generated Id by the database? – Kuldeep S Chauhan Jan 27 '14 at 11:45
  • I've never used SQL server, and don't know if it supports sequences. You can use table generation, which should work on any engine. – JB Nizet Jan 27 '14 at 12:39