两个不同表

时间:2018-01-11 07:54:00

标签: java mysql jpa javax

我正在尝试使用@Entity,@ Table,@ SecondaryTables和@Column注释从3个表中映射实体,如以下示例所示。

表格是:  员工(小学)  2. employee_detail  3. job_description

@Entity    
@Table(name="EMPLOYEE")    
@SecondaryTables({    
    @SecondaryTable(name="EMPLOYEE_DETAIL",    
        pkJoinColumns = @PrimaryKeyJoinColumn(name="EMPLOYEE_ID")),    
    @SecondaryTable(name="JOB_DESCRIPTION",    
        pkJoinColumns = @PrimaryKeyJoinColumn(name="JD_ID"))    
})
public class Employee {

    @Id
    @Column(name = "ID", table= "EMPLOYEE")
    private int id;

    @Column(name = "FIRST_NAME", table = "EMPLOYEE")
    private String firstname;

    @Column(name = "LAST_NAME", table = "EMPLOYEE")
    private String lastname;

    @Column(name = "BANK_ACCOUNT_NO", table = "EMPLOYEE_DETAIL") 
    private String bankacctnumber;

    @Column(name = "JOB_SUMMARY", table = "JOB_DESCRIPTION") 
    private String jobsummary;

    @Column(name = "     ???      ", table = "     ??        ")
    private String uniqueid;

    //getters and setters for above fields
    ...

}

我的问题是,如果我想通过连接

创建字段“uniqueid”

“EMPLOYEE”表中的“ID”列和“JOB_DESCRIPTION”表中的“JOB_CODE”列

此实体对应于以下sql查询字符串(为清楚起见,我使用了字符串构建器): -

StringBuilder sql = new StringBuilder();

sql.append("SELECT");
sql.append(" e.FIRST_NAME AS firstname,");
sql.append(" e.LAST_NAME AS lastname,");
sql.append(" d.BANK_ACCT_NUMBER AS bankacctnumber,");
sql.append(" j.JOB_SUMMARY AS jobsummary,");
sql.append(" CONCAT(e.ID,SUBSTR(j.JOB_CODE,3,8)) AS uniqueid"); 
sql.append(" FROM employee e");
sql.append(" LEFT JOIN employee_detail d ON d.EMPLOYEE_ID = e.ID");
sql.append(" LEFT JOIN job_description j ON j.JD_ID = e.JD_ID ");
sql.append(" WHERE e.ID = 1 ");

究竟应该如何为字段“uniqueid”完成列的映射?这可能吗?

1 个答案:

答案 0 :(得分:1)

这不可能,因为JPA使用映射列进行读写。所以列不能连接。

但是你可以在你的类中编写一个连接字段的简单方法。

另一种可能是使用您的SQL语句的视图,但之后您只能读取并写入,因为该视图包含多个表的字段。