Home > Net >  JPA Using Composite Fields To Store Multiple @Column On An @Entity
JPA Using Composite Fields To Store Multiple @Column On An @Entity

Time:06-24

I have a user table and I am using Hibernate to read it into User instances. I want to collect a number of related columns under a composite object to pass it around. So, I want to do something like this:

@Entity
@NoArgsConstructor
public class User {

    @Id
    private long id;

    @Column
    private String name;

    // A bunch of columns
    ...

    private Statistics stats;
}

Now I want to read some of the columns in the same user table into the fields in my Statistics object.

public class Statistics {

    @Column
    private int x;

    @Column
    private int y;

    // A bunch of columns
    ...
}

Is there a way to achieve that? I don't prefer to use a separate table for statistics and use joins because of some performance concerns. I can obviously move the fields from the Statistics class into the User class but I want to improve the design by using composite objects.

CodePudding user response:

You can check for @Embeddable and @Embedded annotations.

As I remember from top of my head, it should be something like:

@Embeddable
public class PhoneNumber{
}

@Entity
public class Customer
{
    @Embedded
    private PhoneNumber phoneNumber;
}
  • Related