abiieez
abiieez

Reputation: 3189

Composite Keys in Hibernate

I would like to achieve a table as below

   CREATE TABLE `item` (
  `country_id` bigint(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `CREATION_DATE` datetime NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `point` decimal(19,2) NOT NULL,
  `price` decimal(19,2) NOT NULL,
  `UPDATED_DATE` datetime DEFAULT NULL,
  `VERSION` int(11) DEFAULT NULL,
  `STARTER_PACKAGE` tinyint(1) NOT NULL,
  PRIMARY KEY (`name`,`country_id`),
  KEY `fk_country_id` (`country_id`),
  CONSTRAINT `fk_country_id` FOREIGN KEY (`country_id`) REFERENCES `country` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$

Can anyone show me how write the entity with annotation to achieve the above table ?

Upvotes: 0

Views: 277

Answers (1)

overmeulen
overmeulen

Reputation: 1158

Hibernate has a very elegant way of handling this case :

@Entity
@Table(name = "itemPrice")
public class ItemPrice extends PersistentObject {

   @Id
   @ManyToOne
   @JoinColumn(name = "country_id")
   private Country country;

   @Id
   @ManyToOne
   @JoinColumn(name = "item_id")
   private Item item;

   @Column(nullable = false)
   @NotNull
   private BigDecimal point;

   @Column(nullable = false)
   @NotNull
   private BigDecimal price;
}

Upvotes: 1

Related Questions