0

I want to create an entity containing 2 fields that need to be unique in together. One of the fields is a Boolean:

@Entity
public class SoldToCountry {

    private String countryId;


    private Boolean isInt;
}

For a given String there should never exist more than 2 entries one with isInt:true and the other isInt:false.

I read the doc about @Id but it seems that Boolean is not supported. For me it would also be ok to have a unique constraint spanned over both fields and using a generated id.

What is the best way to get this constraint via JPA?

dermoritz
  • 12,519
  • 25
  • 97
  • 185

1 Answers1

1

If your table has really two fields only, and you want they are unique, then they should be the composite PK of the table. Take a look at How to create and handle composite primary key in JPA

If, instead, you have another PK, consider Sebastian's comment.

luca.vercelli
  • 898
  • 7
  • 24
  • it would be nice to see an example with a Boolean as part of a PK – dermoritz Mar 14 '19 at 08:51
  • I think there are not problems with booleans in JPA. Provided that your database supports boolean columns. What DB are you using? (I am talking about using @EmbeddedId, not @Id). – luca.vercelli Mar 14 '19 at 08:57
  • We use Oracle. Thanks i will try. I only read somewhere that only specific bse classes could be part of an id class. – dermoritz Mar 14 '19 at 09:11
  • I am afraid Oracle has no Boolean datatype. Maybe you should change Java datatype to conform to corresponding Oracle column type. – luca.vercelli Mar 14 '19 at 09:24