Understand the Hibernate Framework, an Object-Relational Mapping (ORM) tool for Java, to simplify database interactions. Learn Hibernate's architecture, lifecycle, mappings, and query mechanisms, and apply them to develop a web application with persistent data storage.
Session
objects.hibernate.cfg.xml
or programmatically.save()
, get()
, update()
, delete()
).session.beginTransaction()
, transaction.commit()
, transaction.rollback()
.hibernate.cfg.xml: Configures database connection, dialect, and mappings.
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bookshop</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/example/Book.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Programmatic Configuration (alternative):
Configuration config = new Configuration()
.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver")
.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/bookshop")
.addAnnotatedClass(Book.class);
SessionFactory sessionFactory = config.buildSessionFactory();
Add Hibernate dependencies (e.g., via Maven):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.15.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
Configure IDE (e.g., Eclipse, IntelliJ) to recognize Hibernate configuration files and mappings.
Use Hibernate Tools (e.g., in Eclipse) for generating mappings or reverse-engineering database schemas.
Steps:
hibernate.cfg.xml
with database details.SessionFactory
and Session
in a Servlet or DAO for persistence.Example Servlet:
@WebServlet("/books")
public class BookServlet extends HttpServlet {
private SessionFactory sessionFactory;
@Override
public void init() throws ServletException {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Session session = sessionFactory.openSession();
List<Book> books = session.createQuery("FROM Book", Book.class).list();
req.setAttribute("books", books);
session.close();
req.getRequestDispatcher("/books.jsp").forward(req, resp);
}
}
Book book = new Book();
session.save(book);
session.close()
.session.delete(book);
session.save()
or session.persist()
.session.evict()
or session.close()
.session.delete()
.session.update()
or session.merge()
.