Search code examples
javaspringhibernatejpahibernate-criteria

Can we selectively fetch the columns of an associated joined object in Hibernate?


@Entity
@Table(name = "USER_INFO")
public class User  {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "USER_ID")
    private int userId;

    @OneToOne
    @JoinColumn(name = "CGH_SOE_ID", referencedColumnName = "CGH_SOE_ID", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
    @Fetch(FetchMode.JOIN)
    private UserDimension userDimension;

.......

@Entity
@Table(name = "USER_DIMENSION")
public class UserDimension {

    @Column(name = "EMPLID", length = 11)
    private String employeeLid;

    @Id
    @Column(name = "CGH_SOE_ID", length = 10, nullable = false)
    private String CGHSOEId;

I use Criteria queries to fetch User objects from database and User dimenstion is associated along with it.

1) I want to fetch only 2-3 columns from UserDimension when i fetch user object from database.

2) Can i dynamically switch between all columns fetch and selected columns fetch ?

Thanks


Solution

  • The simplest answer you cannot. Hibernate retrieves all columns mentioned in the entity.

    Possible workarounds:

    1. You can define 2 more entities UserShort and UserDimensionShort based on the same tables but with limited columns.

    2. Use JdbcTemplate where you can fire SQL query (with desired columns only) and add a mapping to get the columns data to the entity fields. (See the example)