In ORM (Object-Relational Mapping) frameworks like Hibernate, common methods are needed to handle CRUD operations (Create, Read, Update, Delete) with objects, avoiding the complexity of manual SQL queries.
- save(): Inserts a new record into the database.
java
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User("John", "Doe");
session.save(user); // Saves user to the database
tx.commit();
2. update(): Updates an existing record.
java
user.setLastName("Smith");
session.update(user); // Updates user's last name to 'Smith'
3. delete(): Removes a record from the database.
java
session.delete(user); // Deletes the user from the database
4. get(): Retrieves a record by primary key.
java
User user = session.get(User.class, userId); // Fetches user by ID
5. load(): Retrieves a proxy for an object, allowing lazy loading.
java
User user = session.load(User.class, userId); // Loads proxy for user
These methods allow you to manage database operations more efficiently.