• Steps to create your first application using Hibernate:
Execute the create statement to create the table – Execute the create statement to create the table- Create your java project
- Add the required jars to your project Add the required jars to your project
- Create a java bean that’ll represent the table
- Create the XML mapping file which should be saved as className.hbm.xml and located near the class
- Create hibernate.cfg.xml to configure the Hibernate
- Create a test class to start inserting objects in the DB.
Create a java bean that’ll represent the table (POJO)
import import java.util.Date java.util.Date;;
public class Employee {
private int id;
private String name;
private Long phone;
private String address;
private Date birthdate ;
this.name = name; }
public Long getPhone(){
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public Employee() {
}
public String getAddress() {
return address;
}
public public int getId() {
return id;
}
private void setId (int id) {
this.id = id;
}
public void setAddress (String address) {
this.address == address;
}
public Date getBirthdate() {
return birthdate ;
}
public String getName() {
return name;
}
public void setBirthdate (Date birthdate) {
this.birthdate =birthdate;
}
}
and Hibernate.cfg.xml will be like
• Create hibernate.cfg.xml
this file is the main configuration file that contain- Driver name
- Data base path
- DB User Name and password
- mapped Tables.
Example :
<hibernate--configuration>
<session--factory name="sessionfactory">
<!-- driver name-->
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- db path-->
<property name ="hibernate.connection.url">
jdbc:mysql://localhost:3306/Hibernate
</property>
<!--DB username / password-->
<property name ="hibernate.connection.username ">root</property>
<property name ="hibernate.connection.password"></property>
<property name ="hibernate.dialect>
org.hibernate.dialect.MySQLDialect
</property>
<!--table mapping-->
<mapping resource="Employee.hbm.xml"/>
</session factory>
</hibernate--configuration>
How to Start the connection ?
- Create Session Factory instance
- get session if exist or open new session;
- begin transaction with the session .
- do you change (persist / update the object
- commit the change
Create a test class
import java.util.Date ;import org.hibernate.Session;
import org.hibernate.SessionFactory ;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args)
{
SessionFactory sessionFactory= new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Employee emp = new Employee();
emp setName("name");
emp.setPhone (new Long(1234567);
emp.setBirthdate(new Date());
emp.setAddress("address");
session.beginTransaction();
session.persist(emp);
session.getTransaction().commit();
System. out.println ("Insertion Done");
}
}
Good luck
No comments:
Post a Comment