Junior — Middle
Kuidas lisada uus üksus andmebaasi Hibernate'i kasutades?
sobes.tech AI
Vastus AI-lt
To add a new entity to the database using Hibernate, follow these steps:
- Create an entity object and fill it with data.
- Obtain a Hibernate session (Session) from the SessionFactory.
- Begin a transaction.
- Call the
save()orpersist()method on the session, passing the entity object. - Commit the transaction.
- Close the session.
Example code:
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
MyEntity entity = new MyEntity();
entity.setName("Example");
session.save(entity); // or session.persist(entity);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
This way, Hibernate will automatically generate the SQL query to insert a new record into the corresponding table in the database.