Sobes.tech
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:

  1. Create an entity object and fill it with data.
  2. Obtain a Hibernate session (Session) from the SessionFactory.
  3. Begin a transaction.
  4. Call the save() or persist() method on the session, passing the entity object.
  5. Commit the transaction.
  6. 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.