5

Address table have following structure with composite keys, user_id is foreign key as well a part of composite PK :

address_ordinal(PK)     user_id(PK, FK)
     1                     1
     2                     1
     1                     2
     2                     2
     3                     2
     1                     3

Address class :

@Entity
public class Address implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private AddressPK id;
}

@Embeddable
public class AddressPK implements Serializable {

    @GeneratedValue  //what strategy ?
    @Column(name="address_ordinal")
    private Integer addressOrdinal; // is there any strategy or any other way to auto generate addressOrdinal based on user_id ?

    @Column(name="user_id")
    private Integer userId;
    //equals() and hashCode()
}

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId;
    //setters and getters
}

In JPA, is it possible to autogenerate one field of composite key based on another field? see above sample data as how it should generate. Basically it is a simple mapping of Users and their multiple Address.
Or do I have to update composite keys manually in Address table?

codeworks elegant
  • 1,051
  • 7
  • 11
  • No. The JPA spec tells you what strategies are provided. Use an event listener and populate it before persist –  Aug 21 '18 at 15:18
  • 2
    @BillyFrost can you please elaborate as how event listener can be implemented to populate composite keys? Currently for adding new users and their corresponding addresses is straight forward. But for adding new address to an existing user I have to fetch the max addressOrdinal first and then persist new address by adding +1 to addressOrdinal. – codeworks elegant Aug 23 '18 at 16:09

0 Answers0