Download Free Java and all books

Pages

Wednesday, 5 September 2012

 

Hibernate Mysql DataBase Using Eclipse

  
• This explains mysql database.

Project Structure:



 JarFiles:


AddStudent.java:•  Here we will use sessionFactory for create connetion My-Sql database.
sessionFactory1 = new Configuration().configure(“com\\xml\\student1.cfg.xml”).buildSessionFactory();
•  Then we will create objects for pojo classes and then save the database using session.
Student1 stu1=new Student1();
s1.save(stu1);
•  Then we will use Transaction statement for begin and commit the database.
Transaction tx1= s1.beginTransaction();
tx1.commit();

01package com.candidjava;
02
03import java.sql.*;
04import java.io.*;
05import org.hibernate.SessionFactory;
06import org.hibernate.Transaction;
07import org.hibernate.HibernateException;
08import org.hibernate.Session;
09import org.hibernate.cfg.Configuration;
10
11public class AddStudent {
12    private static SessionFactory sessionFactory1;
13
14    public static void main(String args[]) throws Exception {
15        if (args[0] != null || args[1] != null || args[2] != null) {// begin if
16                                                                    // A
17            String name = args[0];
18            String name1 = args[0];
19            String degree = args[1];
20            String phone = args[2];
21            System.out.println("Name: " + name);
22            System.out.println("Degree: " + degree);
23            System.out.println("Phone: " + phone);
24
25            if ((name.equals("") || degree.equals("") || phone.equals(""))) {
26                System.out.println("All informations are Required");
27            } else {
28
29                try {// begin try
30
31                    sessionFactory1 = new Configuration().configure(
32                            "com\\xml\\student1.cfg.xml").buildSessionFactory();
33                } catch (Exception e) {
34                    System.out.println("mathan");
35                    System.out.println(e.getMessage());
36                    System.err
37                            .println("Initial SessionFactory creation failed."
38                                    + e);
39
40                }
41
42                Session s1 = sessionFactory1.openSession();
43                Transaction tx1 = s1.beginTransaction();
44                Student1 stu1 = new Student1();
45                stu1.setName(name1);
46                s1.save(stu1);
47                tx1.commit();
48                System.out.println("Added to mysql Database");
49                if (s1 != null)
50                    s1.close();
51            }
52        }// end of if A
53    }// end of method
54}// end of class

Student1.java:

01package com.candidjava;
02
03public class Student1 {
04    private long id;
05    private String name;
06
07    public long getId() {
08        return id;
09    }
10
11    public String getName() {
12        return name;
13    }
14
15    public void setId(long String) {
16        id = String;
17    }
18
19    public void setName(String string) {
20        name = string;
21    }
22
23    public String toString() {
24        return name;
25    }
26}

web.xml:

01<?xml version="1.0" encoding="UTF-8"?>
02<web-app id="WebApp_ID" version="2.4"
05    <display-name>Multiple project Mysql</display-name>
06    <welcome-file-list>
07        <welcome-file>index.html</welcome-file>
08        <welcome-file>index.htm</welcome-file>
09        <welcome-file>index.jsp</welcome-file>
10        <welcome-file>default.html</welcome-file>
11        <welcome-file>default.htm</welcome-file>
12        <welcome-file>default.jsp</welcome-file>
13    </welcome-file-list>
14</web-app>

Student1.cfg.xml:

<session-factory name=”studentFactory”>
Provides a unique name for property used with this database.
<property name=”connection.driver_class”> com.mysql.jdbc.Drive </property>
The property connection.driver_class is used for loading database driver just like loading driver in JDBC(Class.forName();)
<property name=”connection.url”> jdbc:mysql://localhost:3306/test </property>
Connection.url property is used to load connection for the particular database
<property name=”connection.username”> root </property>
This property implies user name of the database.
“root”—This is default user name for mysql.
<property name=”connection.password”> root </property>
This property implies the database password.
root –Replace this with your mysql password.
<property name=”connection.pool_size”>5</property>
Connection.pool_size property is used to maintain connection pooling by application server not by the database server
<property name=”dialect”> org.hibernate.dialect.MySQLDialect </property>
This is an optional property. which generates sql query for database based on the dialect we used. Different database have different query. Query may be change as the database changes. to overcome this problem dialect come in exist.
<property name=”show_sql”>true</property>
This property displays sql query in console generated by the previous property dialect.
If it is false it doesn’t display the query.
<property name=”hbm2ddl.auto”>update</property>
Update–This Property Used to update the table Rather than create the new table.
If table already exists it update values into table otherwise it creates new table automatically.
Create–This property creates new table.
If the table already exists, it deletes all records in the table and create new table with the given values.
It’s better use update property rather than create to maintain old records.
<mapping resource="com\\xml\\Student.hbm.xml"/>
Mapping Resource property is used for mapping pojo with table.
Be sure while com\\xml matches your package name else give your package name instead.
01<!DOCTYPE hibernate-configuration PUBLIC
02    "-//Hibernate/Hibernate Configuration DTD//EN"
04<hibernate-configuration>
05    <session-factory name="student1Factory">
06        <property name="connection.driver_class">
07            com.mysql.jdbc.Driver
08            </property>
09        <property name="connection.url">
10            jdbc:mysql://localhost:3306/test
11
12        </property>
13        <property name="connection.username">
14            root
15        </property>
16        <property name="connection.password">
17            root
18        </property>
19        <property name="connection.pool_size">5</property>
20        <!-- SQL dialect -->
21        <property name="dialect">
22            org.hibernate.dialect.MySQLDialect
23            </property>
24        <!-- Echo all executed SQL to stdout -->
25        <property name="show_sql">true</property>
26        <property name="hbm2ddl.auto">create</property>
27        <mapping resource="com\\xml\\Student1.hbm.xml" />
28    </session-factory>
29</hibernate-configuration>

Student1.hbm.xml:

01<?xml version="1.0"?>
02<!DOCTYPE hibernate-mapping PUBLIC
03    "-//Hibernate/Hibernate Mapping DTD//EN"
05<hibernate-mapping>
06    <class name="com.candidjava.Student1" table="test.Student">
07        <id name="id" type="long" column="ID">
08            <generator class="increment" />
09        </id>
10        <property name="name" column="name" not-null="true" />
11
12    </class>
13</hibernate-mapping>

OUTPUT:

 

 
 
 

1 comment:

Unknown said...

This is the best solution to inser record into database table