Hibernate 中 save() 和 persist() 的區別
Save() 和 persist() 這兩種方法都用於將物件儲存到資料庫中。
根據文件 -
Save() - 持久化給定的瞬時例項,首先分配一個生成的識別符號。(或者如果使用分配的生成器,則使用識別符號屬性的當前值。)如果關聯映射了 cascade="save-update",則此操作會級聯到關聯的例項。
根據文件 -
persist() - 使瞬時例項持久化。如果關聯映射了 cascade="persist",則此操作會級聯到關聯的例項。此方法的語義由 JSR-220 定義。
| 序號 | 關鍵 | save() | persist() |
|---|---|---|---|
1 | 基本 | 它將物件儲存到資料庫中 | 它也把物件儲存到資料庫中 |
2 | 返回型別 | 它返回生成的 ID,返回型別是可序列化的 | 它不返回任何內容。它的返回型別是 void。 |
3 | 事務邊界 | 它可以在邊界內和邊界外儲存物件 | 它只能在事務邊界內儲存物件 |
4. | 分離的物件 | 它將為分離的物件在表中建立一個新行 | 它將為分離的物件丟擲永續性異常 |
5. | 受支援 | 它僅受 Hibernate 支援 | 它也受 JPA 支援 |
Hibernate 中 Save 的示例
@Entity
public class User {
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class SaveExample {
public static void main(String[] args) {
//get session factory to start transcation
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setId(1)
user.setName("ABCD")
session.save(user);
//Close resources
tx.commit();
sessionFactory.close();
}
}Hibernate 中 Persist 的示例
@Entity
public class User {
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class PersistExample {
public static void main(String[] args) {
//get session factory to start transcation
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setId(1)
user.setName("ABCD")
session.persist(user);
//Close resources
tx.commit();
sessionFactory.close();
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP