This article is about hibernate practical example. Below is an example of hibernate with my sql using hibernate annotations.
Here is the Student bean class with id and name properties with annotations.
- package beans;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.Table;
- @Entity
- @Table(name="student_master")
- public class Student {
- @Id
- @GeneratedValue
- @Column(name="stud_id")
- private long id;
- @Column(name="name")
- private String name;
- /**
- * getters and setters
- * @return
- */
- public long getId() {
- return id;
- }
- public void setId(long id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
Here is the hibernate.cfg.xml file. For this example mysql used as the data base.
- <?xml version='1.0' encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.connection.password">root</property>
- <property name="show_sql">true</property>
- <property name="hibernate.hbm2ddl.auto">create</property>
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <mapping class="beans.Student"/>
- </session-factory>
- </hibernate-configuration>
Here is the Driver class. In the driver class we have created an instance of student and saved to the database.
- package driver;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import beans.Student;
- public class Driver {
- /**
- * main method
- */
- public static void main(String[] args) {
- Session session = null;
- try {
- //getting session factory instance
- SessionFactory sessionFactory = new Configuration().configure(
- "hibernate/hibernate.cfg.xml").buildSessionFactory();
- session = sessionFactory.openSession();
- session.beginTransaction();
- //student instance
- Student student = new Student();
- student.setName("Sanjay ");
- session.save(student);
- session.getTransaction().commit();
- } catch (Exception e) {
- System.out.println(e.getMessage());
- } finally {
- session.flush();
- session.close();
- }
- }
- }
Your Suggestions Are Always Welcomed.