Reputation: 1659
I have roughly 100,000 Objects that I want to insert into the database. I would like to leverage Spring/Hibernate and create List<MyPojo>
and use session.saveOrUpdate()
to perform the insert.
However, the MyPojo object contains about 25 foreign keys. To perform that many lookups by Id to get the actual referenced object would be extremely inefficient.
Therefore I'd like to just use the foreign key ids (the same way that it would be stored in the database) rather than load every object.
Outside of running native queries, is there another solution to do this?
Thanks!
Upvotes: 2
Views: 2339
Reputation: 4989
You can do this by mapping the foreign key and the object, but marking the object as lazy and not "updatable" and not "insertable".
Here is the object, but not used for writing the values.
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MY_POJO_FK", insertable = false, updatable = false)
private MyPojo myPojo;
Below is the foreign key mapped normally
@Column(name = "MY_POJO_FK")
private Long myPojoFK;
The downside of this approach is you have to update the foreign objects individually (no cascading), but the advantage is you will not load the foreign objects until you need them.
If you are only mapping this to write data, you don't need to worry about mapping the object at all.
Upvotes: 3