简体   繁体   中英

Define hibernate entity from 3 tables

I'm working on a legacy application and I was asked to integrate Hibernate (this is my first time working with it). This app has 3 tables (among others) as follows:

Table SITE             Table PARAMS        Table TRANS
==========             ==============      ===============
pk: id (INT)           pk: p_id (INT)      pk: t_id (INT)
    lang_id (INT)      name (CHAR)         fk: p_id (INT)
                       value (INT)         fk: lang_id (INT)
                                           text (CHAR)

Then I need to get the parameters from PARAMS along with their translations, stored in TRANS, according to the language defined for the application, which is stored in SITE.

I've been struggling trying to understand how to make a join of the tables to get the data for the entity. I tried using @JoinTable , but I couldn't figure out how to make a 3-way join, so I started trying with @SecondaryTables without luck.

I defined this entity to map the requested data (I know this won't work as it is now) and I'm trying to figure out the proper way to make the join.

@Entity
@Table(name = "params")
@SecondaryTables(
{
    @SecondaryTable(name = "trans", pkJoinColumns = @PrimaryKeyJoinColumn(name = "p_id")),
})
public class Tparam implements Serializable
{
    @Id
    @GeneratedValue
    @Column(name = "p_id")
    private int id;

    @Column(name = "name")
    private String Name;

    @Column(name = "text")
    private String visibleText

    ...
}

Any help is appreciated!


For reference, this SQL query gives me what I want:

SELECT * FROM params, lang, site WHERE params.p_id = lang.p_id AND lang.lang_id = site.lang_id;

You need to define 3 entities :

1-Param 2-Lang 3-Site

@Entity
@Table(name = "params")
public class Tparam implements Serializable
{
    @Id
    @GeneratedValue
    @Column(name = "p_id")
    private int id;

    @Column(name = "name")
    private String Name;

    @Column(name = "text")
    private String visibleText

    ...
}

@Entity
@Table(name = "lang")
public class Lang implements Serializable
{
    @Id
    @GeneratedValue
    @Column(name = "lang_id")
    private int id;

    @ManyToOne
    @JoinColumn(name = "p_id")
    private Tparam param;

    ...
}

@Entity
@Table(name = "site")
public class Site implements Serializable
{
    @Id
    @GeneratedValue
    @Column(name = "site_id")
    private int id;


    @ManyToOne
    @JoinColumn(name = "lang_id")
    private Lang lang

    ...
}

Then, when you need the data you can use Criteria (or Query) on Site entity to fetch data. Each record of site contains one Lang and each of them contains one Tparam .

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