Unique constraint not created in JPA

2019-02-22 01:55发布

I have created the following entity bean, and specified two columns as being unique. Now my problem is that the table is created without the unique constraint, and no errors in the log. Does anyone have an idea?

@Entity
@Table(name = "cm_blockList", uniqueConstraints = @UniqueConstraint(columnNames = {"terminal", "blockType"}))
public class BlockList {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name="terminal")
    private Terminal terminal;
    @Enumerated(EnumType.STRING)
    private BlockType blockType;
    private String regEx;
}

5条回答
Evening l夕情丶
2楼-- · 2019-02-22 02:35

More suggestions than a real answer...

  • you should clarify which JPA provider (and the version) you are using for such questions.

  • I notice that one of your column is part of a ManyToOne association, this might be a "special" case not well handled by your JPA provider. By not well handled, I mean bug. I'd check the issue tracker for an existing issue (and maybe create a new one, your case seems JPA compliant).

查看更多
可以哭但决不认输i
3楼-- · 2019-02-22 02:41

If you want the unique constraint, you should do it by sql:

ALTER TABLE cm_blockList ADD CONSTRAINT cm_blockList_unq UNIQUE (terminal);

See also: https://stackoverflow.com/a/3498242/1244488

查看更多
4楼-- · 2019-02-22 02:47

You dont have to drop everything, just drop this particular table you want to create unique index for

查看更多
Rolldiameter
5楼-- · 2019-02-22 02:48

I also faced the same issue, but adding unique-key="UK1_test" in the mapping file worked fine.

<property name="hibernate.hbm2ddl.auto">create</property> with unique-key="UK1_test" unique="true" in the mapping file created alter table employee add constraint UK1_test unique (addrId)

查看更多
虎瘦雄心在
6楼-- · 2019-02-22 02:56

Well, I found another way to make the design. More because the design evolved than a work around.
I heard however from a colleague, that had had the same problem, that unique constraint only are created by hibernate (we are running JBoss 4.3) when the entire database is created. It will not work when you create a new table in an existing database.
So in persistence.xml it is necessary to set hibernate.hbm2ddl.auto to create-drop to make it work. I can not confirm this though.

查看更多
登录 后发表回答