开发者

which solution is good practice hibernate save data in database?

开发者 https://www.devze.com 2023-03-01 13:53 出处:网络
I have two entities which are Student and Class entities. Student and Class are many to one relationship. So student contains class attribute.

I have two entities which are Student and Class entities. Student and Class are many to one relationship. So student contains class attribute.

Now i want to save or create a student associate with existing class(means i know primary key ID already).

Solution 1:

Student student = new Student();
Class class = session.load(classId);  
student.setClass(class);
session.save(student);

Solution 2:

Student student = new Student();
Class class = new Class();
class.setClassId(classId);
student.setClass(class);
session.save(student);

My question here is in solution 1 it will issue two SQL, one is to get Class another is to insert student. But in solution 2 only need to have one SQL. If I have more class attribute, i will 开发者_如何学Cload and issue more select sql before insert. It seems not that efficient. Is there any side-effect in solution 2?

which way to do save/insert is better? By the way, i do not set up cascade.

Thank you Yee Chen


Solution 1 won't issue an SQL query to load Class. Unlike get(), load() returns a proxy object with the specified identifier and doesn't perform a database query immediately. Thus, load() method is a natural choice for this scenario (when you actually need to load an object, use get()).

Possible side effect of solution 2 depends on cascading configuration of relationship and so on. Even if it works fine in your current case, it makes your code more fragile, since seemingly unrelated changes in the code may break it.

So, I recommend you to use Solution 1 and don't worry about performance.


Is there any side-effect in solution 2?

First of all, you haven't associated your student with any class there.

Secondly, where do you get that class id from in the general case? At some earlier point in time, you had to either fetch an existing class instance from the DB, or create a new instance and persist it, so that you get its id. Of course, reusing an entity you already have is fine, but juggling with ids like you do above is IMHO not.

Thirdly, it is not a good idea to prematurely optimize your app. Get it to work properly first, then measure performance, and optimize only if and where needed.

0

精彩评论

暂无评论...
验证码 换一张
取 消