entitymanger.find使用外键主键执行查找查询

时间:2018-08-24 03:59:52

标签: java mysql hibernate

我想使用主键获取EventDate的对象。以下是我正在执行的查询

EventData eventData = entityManager.find(EventData.class, eventdataid);

在控制台中执行此命令后,我得到的查询为

select eventsajgj0_.FILE_ID as FILE_ID8_14_0_, eventsajgj0_.id as
id1_12_0_, eventsajgj0_.id as id1_12_1_, eventsajgj0_.CODE as CODE2_12_1_,
eventsajgj0_.DATE as DATE3_12_1_, eventsajgj0_.FILE_ID as FILE_ID8_12_1_,
eventsajgj0_.MILLIS as MILLIS4_12_1_, eventsajgj0_.ORDER_NR as
ORDER_NR5_12_1_, eventsajgj0_.TYPE as TYPE6_12_1_, eventsajgj0_.VALUE as
VALUE7_12_1_ from eventdata eventsajgj0_ **where eventsajgj0_.FILE_ID=?**
order by eventsajgj0_.ORDER_NR

请注意,上述查询中的where子句是针对file_id(外键)而非id(eventdata主键)的

dao结构如下

public class EventData implements Serializable {

        private static final long serialVersionUID = 1L;

        public EventData() {

        }

        @Id 
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;

        @ManyToOne(fetch=FetchType.EAGER)
        @JoinColumn(name="FILE_ID")
        private ApplicationFile file;
       getter & setters

    }

public class ApplicationFile implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    bi-directional many-to-one association to Event
    @OneToMany(mappedBy="file", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @OrderBy("orderNr")
    private List<EventData> eventsajgjd;
    getter & setters
}

我的问题是,当我在eventdata表上执行查询时,为什么使用file_id而不是id进行查询。

PS:如果我将ApplicationFile的提取类型更改为LAZY,则执行的查询位于id上,而不位于file_id上​​。

(从评论中添加):

CREATE TABLE eventdata (
    ID int(11) NOT NULL AUTO_INCREMENT, 
    FILE_ID int(11) DEFAULT NULL, 
    PRIMARY KEY (ID), 
    KEY eventdata_ibfk_1 (FILE_ID), 
    CONSTRAINT eventdata_ibfk_1 FOREIGN KEY (FILE_ID)
               REFERENCES files (ID) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=297502 DEFAULT CHARSET=utf8

1 个答案:

答案 0 :(得分:1)

我敢打赌,因为您是双向映射EventData / ApplicationFile(您在List<EventData>实体中拥有ApplicationFile类型的属性

因此,加载EventData意味着热切加载相关的ApplicationFile,并热切加载所有相关的EventData

我想相关的ApplicationFile实例已经在EntityManager L1缓存中(否则该查询应加入文件表中)