简体   繁体   中英

Projection on hibernate relationship annotation

I have a two tables which are represented as below:

tableA {

private String code;
private String desc;
//few other properties followed by getter and setter
}

tableB {

private String code;
private String desc;
private String tableACode;
//few other properties followed by getter and setter
}

Now, I wanted to define a @ManyToOne relationship in tableB for tableA such that I wanted to store only the tableA.desc (I wanted to limit the size of this object in memory when it is cached).

Is this possible to do so?

I tried something like below.. But the resulting query is not what I'm expecting.

tableB {

private String code;
private String desc;
private String tableACode;


@ManyToOne
@JoinColumnsOrFormulas(value = {@JoinColumnOrFormula(column=@JoinColumn(name = "tableACode", referencedColumnName = "code")),
        @JoinColumnOrFormula(formula = @JoinFormula(value = "SELECT a.desc from tableA e WHERE a.code = tableACode", referencedColumnName = "tableACode"))})
private String tableADesc;
//few other properties followed by getter and setter
}

It's possible, only if you create the EntityA to contain only the:

  • id
  • desc

Then you can simply use a @ManyToOne in EntityB:

@ManyToOne
private EntityA entityA;

So, even if your EntityA database table has multiple columns, you only persist the desc .

For new EntityA entries, all non-persisted columns will be set to NULL, which may break some NOT NULL constraints, so be aware of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM