Make new Proteus device with its PCB package. (Here for 7 segment display))

I am here after long long long time. Therefore I thought post a valuable thing which I have done with proteus. That is making a new device for proteus. One day I had needed to design a PCB which including seven segment displays. But I couldn't find any Proteus PCB package which is match with 15.24mm seven-segment display pin-out. Therefore I encouraged to create a PCB package for a seven segment display. So following steps will describe to create a new PCB package which totally match with your particular hardware device.

Steps to create PCB package for seven segment display

Step 1- Import a seven segment display to Proteus device list from existing devices to modify it. For that simply go to Library->Pick device/Symbol... (or press P) and then type 7SEG-COM-CAT then it will provide all the available Common Cathode 7 segments with different colors. Choose a one of the device then press ok.

Step 2- Then draw the imported seven segment to the sheet. Now we can modify the device in order to meet our actual hardware device's requirements (pin numbers, common pins,etc...). Then right click on it and select Decompose to modify it

Step 3- This seven segment display has only 8 pins but in actual 7 segment display has 10 pins which are 7 input pins, 2 common cathode pins, and dot input pin (DP). Therefore first we need to modify this device to make additional 2 pins. So you can just add another 2 pins from the tool bar to the device. The tool to add pins and the modified 7 segment display are,



Now you have carried out the requirement for number of pins of the device.

Step 4- But still we do not assign the actual pin numbers for the device. This will need to define PCB package for this device. Now double click on a pin to define the pin number. It will display a widow which asking the pin name and number. Type the pin numbers for the particular pin name (A-7, B-6,...) as describe in following figure. (Do not care about other options in the window.)

But there is an exception... What should be the names for pins those we have drawn on the sheet? so you can put any name for DP pin BUT you should put the name for our second common cathode pin as the name of the pin which already exists as a common cathode. (Because they are common pis) For my Proteus it is COM, so I put COM for name of the second common cathode pin.



Now configurations for this device is completed at here.

Step 5- Now start Proteus ARES to make our PCB package for this device. Here we do not have a package as just like in previous situation to modify it. So we have to make our own package from the beginning. Therefore you will need the distances between pins and other dimensions to draw the PCB package of your device. So you can download the data sheet of your 7 segment display to obtain the dimensions. My 7 segment is 15.24mm one and its dimensions are,


Step 6- First of all press M to change the scale to mili meters (It will display on the right bottom of the ARES window and you can use several grid scales from View->Snap 0.1mm , Snap 0.5mm , etc..) Draw the pin holes using Square or Circle pad mode. Also you can use Dimension mode to measure the distance from one place to another. Carefully draw the diagram with correct measurements. Then assign pin numbers by double clicking on a pin.


Then you can use other 2D graphics to make your package nice.


This number (8) , square and dot are 2D graphics only but it will make beautiful when you view this as a 3D view.

Step 6- Then select all drawn component and Right click and select Make package. Then fill the text boxes with particular data. You can use any name for your package name and other things (These are only depend on categorizing your component in the Proteus library). Then press Ok to make the package.


Now we have our own PCB package for 7-segment display. So now we can make our 7-segment device which is modified earlier in Proteus isis.

Step 7- Then go back to our ISIS design window and make a device by selecting all drawn components, right click and select 'Make device' from popup menu. Now you can see following window. Before that it will show you a warning message Just click ok to ignore that.


Type any unique name on the Device name field and Type a letter on 'Reference Prefix'. This is the letter you can see when draw a new device of your device such as D1, D2, D3.... Then click next.

Then it will show a black window with a text as "ARES PCB libraries are not installed or the specified package cannot be found in any library". So to add our already created PCB package to this device click on "Add/Edit" button.

Then click on Add button to add a PCB package. After that it will show a window named "Pick package" then type the name you have given in the Proteus ARES as the 'Keyword' and select that package. Now Proteus load your package for you and show it in the black area of the window as follows.

Now click on 'Assign package(s)' button to add this package to this device. Now you can see the PCB footprint on the black area which show a message(ARES PCB libraries are not installed or the... ) earlier. Then click next, next... and Ok to finish the wizard. and now you have a 7-segment display with your own PCB package.

Step 8- Choose this device from pick device window and place it on the sheet and you can create a PCB also using this device. This is the solution for our problem here. So enjoy it.........

This is a PCB which I created using above method (ISIS schematic design and PCB design)

Continue Reading...

Revert Ubuntu boot loader after installing Window 7

This post will describe to install Ubuntu GRUB boot loader after installing windows 7 on a PC that already Ubuntu installed. Also this is a problem that I faced after installing Windows 7. Suddenly my Windows 7 installation was crashed and I formatted Windows installed drive and reinstall the Windows 7. I was used Windows and Ubuntu installed on different drives as a dual boot. But after installing windows 7 Ubuntu boot loader was overwritten by windows boot loader and that boot loader does not list my Ubuntu installation. Therefore I could not select Ubuntu to load and windows boot loader automatically boot the Windows7 itself. To overcome this problem we have to overwrite GRUB boot loader on windows boot loader. Follow the steps that I explained bellow correctly to do that.

This method will copy boot settings from Ubuntu Live-CD in order to boot from GRUB boot loader.

Step1- Insert Ubuntu Live CD into CD drive and boot from it.



Step2- Click on 'Try Ubuntu' (on Ubuntu 11.04) to load Ubuntu from Live CD without affecting to your computer.










Step3- When Ubuntu Live desktop appear Run 'Terminal' (Application-->Accessories-->Terminal) to execute following commands.
Step4- In terminal type sudo fdisk -l
It will display all partitions on the hard disk with some details
Identify the partition which Ubuntu installed by checking 'System' column from the above result. The partition which has 'Linux' under system column is the partition of Ubuntu installed.

But here(in my computer) 3 partitions hold 'Linux' under system column. Therefore you should identify the correct partition. For that you can use 'Disk utility' software(it is already included in Live-CD session). Still complicated to identify the partition please be patient, it can be identify in next step.


Step5- Mount the Ubuntu partition drive
    sudo mount /dev/sdXX /mnt
    (Example- sudo mount /dev/sda9 /mnt)

Now go to Home directory(Place-->Home), go to root directory and go to mnt directory by double clicking. Make sure here the folders such as 'boot', 'opt', 'usr' and 'bin' etc exists on this directory(/mnt directory). If not you could not mount Ubuntu installed partition to the mnt, so unmount it and mount the correct partition to the mnt.(To unmount type sudo unmount /mnt)

Step6- If you have different partitions for boot, home, etc... mount them to each corresponding directory in /mnt directory.
Example- sudo mount /dev/sda3 /mnt/boot
                sudo mount /dev/sda10 /mnt/home
(to check whether you mount correct partition to the correct directory check out the content of each directories)

Step7- Now all the files that are required had mounted and ready to install GRUB boot loader.

sudo grub-install --root-directory=/mnt /dev/sda

(Note-That's /dev/sda the hard disk itself, not Ubuntu installed partition)
If it says grub-install is not a command then you had some mistake on mounting.

Step8- Unmount and restart
    unmount all the partitions that mounted.
    Restart the computer - sudo reboot


That's it. Now you can see the GRUB boot loader with all the installed operating system listed.
Continue Reading...

Use Android phone as a modem (Internet connection to PC through Android phone)

First of all I would like to say happy new year to all of you. So this is my first post in 2012.

This post is based on a problem that I faced after -->brought an Android phone. Oh I forgot to say you, I brought an Android phone it is Sony Ericsson Experia X10 mini pro. The problem that I faced is 'How to connect this phone and establish a internet connection in PC'. You know most of the normal phone that capable GPRS can connect to PC(USB or bluetooth) and establish the internet connection over phone. Earlier I used a Nokia phone(Nokia 3120 classic). It can be used as a modem to pc, therefore I could brows internet in PC through the phone.
But in this Android phone it is a little bit different. Because this is an Android phone *#%@.=+.

Simply here are steps to configure your Android phone as a modem.

First of all you have to download and install software needed in both sides, phone and PC. This task is just like a client-server application. So first, lets install on the phone.

The software is EasyTether. EasyTether allows you to shares your phone Internet connection with computer/laptop/notebook (Windows 7/Vista/XP 64-bit/32-bit, Mac OS X 10.4/10.5/10.6/10.7, Ubuntu 10.4+, Fedora 13+)

you can download Easy Tether from Android market and install it from your phone it self. But there is a thing to say you this is not a Free software. But Lite version of Easy Tether is available in Android market but the latest version of the EasyTether Lite has some restrictions since it is lite version. Such as blocking secure HTTP sites....... Therefore this is not a complete solution. But there is a way to Activate the EasyTether. Follow these steps to achieve the EasyTether.

The older version of the EasyTether has the Activation code for full version. Therefore you have to install an older version of Easy tether to get the code.

  • First download EasyTether 0.9.3 apk file from here or here.
  • Install the apk file manually to the phone.
  • Open the EasyTether from the phone ans just go to 'About' page and write down 5 digit code (under 'Registration code'). So this is the activation code for your phone.
  • Now uninstall EasyTether 0.9.3 from your phone to install latest version.
  • Install latest version of the EasyTether Lite version(free version)from the Android market.
  • Open it. In first start, EasyTether will show a dialog box about a setup wizard or some thing like that. Just cancel it(You can get it later from setup) and tap on 'Activate EasyTether' to activate the product.
  • Here you should type the 5 digit number which you written under 'Activation code'
  • Now you have the full version of the EasyTather with all capabilities.

Now tap on 'Setup/Settings' and tap on 'USB Tethering setup' to configure your computer for EasyTether. now a setup wizard for the configuration will open and you can easily follow the instruction. This setup wizard is more descriptive and easy. Therefore I think that is no need to explain these steps here. Additionally you have to download the EasyTether software for PC.(The setup wizard will inform you to download and install it to your PC).

Additionally make sure the network drivers installed on your PC. In Windows you can be found it in 'Device manager' under 'Network adapters' named 'Easy Tether Network Adapter'.

Finally you will be able to connect to internet through your Android phone.

To establish the connection just plug USB cable and click on 'Connect' by right click on the EasyTether icon from sys tray in Windows.


Continue Reading...

Hibernate operations (Data Deletion) - Part 4

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data retrieving through hibernate. (Data insertion article can be found at Part 1 of this series and data update article can be found at Part 2 of this article series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"


package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)


Data Deletion

Before writing codes for data deletion, you should have a knowledge about HQL for the hibernate. This HQL can be use to data retrieve,update and delete from db. If you do not have at least basis of the HQL please refer part 2 of this article series.


So, now let move to data deletion, this deletion is also a some kind of update to the db. Because deletion means removing specific field or fields from a table by changing its status (status means number of fields, file size, etc). Therefore the method that we used for update the db can be used for data deletion also. Here code for data deletion is not much differ from data updating.

Therefore the HQL query for data deletion is,

delete from Person

If we use this query itself for data deletion, the query will delete the current element from the table. But this thing won't be used for practical scenarios. Therefore we have to let it know 'what records to be deleted' by executing the query.

HQL query for data deletion with conditions

delete from Person as p where p.id = :key

Here I used the parameter(if you can remember) for this query named 'key'. (Need 'what is the parameter?' please refer part2 of this article series). Therefore the complete java code for this query is,


String searchId = "1";
String query = "
delete from Person as p where p.id = :key";

session.createQuery(query).setString("key",
searchId).executeUpdate();

Simply this is the way to update the database also, only change of this code is the word 'delete' in the query. Isn't it easy?...........But finally remember to commit the operation because 'we change the database's data'.

The complete java code for data deletion is,

package pkg;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {
       
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
       
        SessionFactory factory = config.buildSessionFactory();
             
        //beginning of the session
        Session session = factory.openSession();
        session.beginTransaction();//beginning of the transaction
       
       
String searchId = "1";//this is the key id for field being updated
       
        //create the delete query
       
String query = "delete from Person as p where p.id = :key";
       
       
session.createQuery(query).setString("key", searchId).executeUpdate();
        

        session.getTransaction().commit();//end of transaction
        session.close();//end of  session
       
       
        }

}

If you execute this code segment the field with id of  "1" will be deleted (if exist).
Also I have to mention here the method createQuery() will return the number of fields that it changed by executing the query. Therefore if you want to get the number of fields that changed or check whether any changes had been done by the query, you can use that number. To do that first assign the number return by method to the int variable.

int fieldCount = session.createQuery(query).setString("key", searchId).executeUpdate();

After that you can use this variable for get the number of fields that changed or check whether any changes had been done by the query.

For example,

int fieldCount = session.createQuery(query).setString("key", searchId).executeUpdate();

if(fieldCount > 0)
    System.out.printf("Number of fields changed %d\n", fieldCount);
else
    System.out.printf("No changes had been done\n");

Hmmmmm.... so this is the last article for hibernate operation article series. If you go through all the parts of this article series you will be able to do basic hibernate operations such as,
  • Data insertion.
  • Data updating
  • Data retrieving
  • Data deletion.


Related posts
Continue Reading...

Hibernate operations (Data Retriving) - Part 3

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data retrieving through hibernate. (Data insertion article can be found at Part 1 of this series and data update article can be found at Part 2 of this article series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)

Data Retriving
Before writing codes for data retrieving, you should have a knowledge about HQL for the hibernate. This HQL can be use to data retrieve from db. If you do not have at least basis of the HQL please refer part 2 of this article series.

It is very easy to retrieve data from the db by just executing HQL query but getting data in java program from the result of the executed query is some what hard.

The query for retrieve all data from Person class is,

from Person

This query can be execute by executing following java code segment.

String query = "from Person";
session.createQuery(query);

These codes will be executed successfully but where is the result which returned from the executed query?
In hibernate the result of the HQL query can be caught by java.util.List. Therefore code for retrieving data can be update as follows.


Now list object hold the all of data which return from the executed query.

Now let's see how to access to the list in order to get the real data. To acquire this we have to use java.util.Iterator class. So do not forget this is Hibernate(a ORM tool) therefore we can use getters from 'Person' class to get the particular data. If we going to use getters, it should be included some data into instance variables in the class. Therefore we can assign data into Person type object.

String query = "from Person";
List list = session.createQuery(query).list();
       
Iterator iterator = list.iterator();

Person obj = (Person) iterator.next();//cast and assign data to Person type object

System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");

We can use while loop to view all data on the result set.

String query = "from Person";
List list = session.createQuery(query).list();
       
Iterator iterator = list.iterator();

while (iterator.hasNext()) {
        Person obj = (Person) iterator.next();//cast and assign data to Person type object
           
        System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
}

Also you can implement conditional retrieving using 'where' keyword.

String searchId = "1";
String query = "from Person as p where p.id = :sId";
List list = session.createQuery(query)
        .setString("sId", searchId).list();
       
Iterator iterator = list.iterator();
       
while (iterator.hasNext()) {
        Person obj = (Person) iterator.next();//cast and assign data to Person type object
           
        System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
}

The complete java code for data retrieving is,

apackage pkg;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
//import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
             
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();


        session.beginTransaction();

        String searchId = "1";
        String query = "from Person as p where p.id = :sId";
        List list = session.createQuery(query)
                    .setString("sId", searchId).list();
       
        Iterator iterator = list.iterator();
       
        while (iterator.hasNext()) {//is next data exist? then loop
            Person obj = (Person) iterator.next();//cast and assign next data to Person type object
           
            System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
        }
       
        session.close();

Now as an example let's consider our table data are looks like this,

+----+-----+-------------------+
| id | age | name              |
+----+-----+-------------------+
|  1 |  23 | Milinda           |
|  2 |  24 | Milinda Aruna     |
|  4 |  25 | Aruna Milinda UWU |
|  5 |  25 | Aruna UWU Milinda |
+----+-----+-------------------+
The output of this code segment is,

1    23    Milinda

Related posts
Continue Reading...

Hibernate operations (Data Update) - Part 2

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data update through hibernate. (Data insertion article can be found at Part 1 of this series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)

Data Update
Before writing codes for updating let me introduce the HQL for the hibernate. This HQL can be use to update the db. It is essential to get know about HQL  before move to further operations of hibernate.

HQL - The Hibernate Query Language
HQL is similar in appearance to SQL that can be used as a a powerful query language for Hibernate.HQL is a case insensitive query language. Therefore as an example the keyword fRoM, FrOm, from and FROM are identical for a query.

The first HQL query.

from
from is the simplest possible Hibernate query. Let's clarify this by using few examples.

from Person

This will return all the data from Person table. The equaling sql query is,

/*this is equaling sql query for 'from Person'*/
select * from Person

In order to refer to the Person in other parts of the query, you can assign an alias for Person using 'as' keyword.

from Person as P
/*Now P refer the Person table*/

Also this can be acquired without using 'as' keyword.

from Person P
/*Now P refer the Person table*/

Parameters
These parameters can be used within the the query to pass values when they are executing in the java program.

The sign  :  used to define the parameters.

from Person as p where p.id = :personId

Here 'personId' is a parameter. Now lets execute a HQL query in java. Basically to execute a HQL query the method 'createQuery' in the class 'org.hibernate.classic.Session' is used.

String searchId = "1";
String query = "from Person as p where p.id = :personId";

session.createQuery(query).setString("personId", searchId);

When call the method 'createQuery' the value of 'searchId' will assign to the parameter 'personId' in the query. Finally the query for execute is,

from Person as p where p.id = 1

Now let's combine update and these 2 concepts to execute the update query. 'createQuery' method can be used execute the update query. A update query uses the keyword 'update' as follows


'keyId' is a parameter for the query which can be used to pass a value when it execute.

The complete java program for the update is,

package pkg;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {
       
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
       
        SessionFactory factory = config.buildSessionFactory();
             
        //beginning of the session
        Session session = factory.openSession();
        session.beginTransaction();//beginning of the transaction
       
        String name = "New_Milinda";//this is new name for 'id'
        String id = "1";//this is the key id for field being updated
       
        //create the update query
        String query = "update Person as p set p.name = :newName where p.id = :keyId";
       
        session.createQuery(query)
            .setString("newName", name)//this will set the string 'newName' to name variable
            .setString("keyId", id)
            .executeUpdate();
        

        session.getTransaction().commit();//end of transaction
        session.close();//end of  session
       
       
        }

}

After this code segment run the data's which having id equal 1 will change its name into 'New_Milinda'. Here I used 'where' keyword to implement the condition for the update. (similar method used in mysql queries)

Finally the query to be executed is,

update Person as p set p.name = New_Milinda where p.id = 1

Also this is the query after setting all the parameters(newName and keyId).


I hope to post more articles for other operations of hibernate such as
  • Data retrieve
  • Data delete
from the db. Will be soon........

Related posts

Continue Reading...

Hibernate operations (Data insertion) - Part 1

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data insertion to the db through hibernate.

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

Hibernate is a ORM tool. Therefore it is not necessary to care about db type (whether MySql or derbydb or another) when you programming a application for a db. But you have to concern only about the 'connection.driver_class' and 'connection.url' in the 'hibernate.cfg.xml' file to match the db type.

Therefore you can change your database type at anytime without changing whole java codes or queries written for da operations. It is the power of Hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.

Data insertion
Data insertion can be done using this persistent class's object. Following sample code shows the way to insert data to a database through hibernate.

 Create a java class named "TestPerson.java" with main method.

package pkg;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

 public static void main(String[] args) {

  //create configurations for Person class
  AnnotationConfiguration config = new AnnotationConfiguration();
  config.addAnnotatedClass(Person.class);
  config.configure("hibernate.cfg.xml");

  //create new schema(db and table)
  new SchemaExport(config).create(true, true);//comment this line if you already created the table Person
 
  SessionFactory factory = config.buildSessionFactory();
  Session session = factory.getCurrentSession();
 
  session.beginTransaction();//begin the db operations
 
  //Insertion to the table
  Person person = new Person();//create the object from persistent class
  //set data that you want to store in db
  person.setId(1);
  person.setName("Milinda");
  person.setAge(24);
  
  session.save(person);//save the object to db
 
  session.getTransaction().commit();//save permanently to db(end of db operations)
 }
}

Now data(id=1, name=Milinda and age=24) will be stored in the 'Person' table. Finally the 'Person' table's data can be shows as follows.

+----+-----+----------+
| id | age | name     |
+----+-----+----------+
|  3 |  24 | Milinda  |
+----+-----+----------+

Note- You can remove(or comment) the code line new SchemaExport(config).create(true, true); if you already create the db and particular tables.(This code line responsible for create tables on th db)

I hope to post more articles for other operations of hibernate such as
  • Data update
  • Data retrieve
  • Data delete
from the db. Will be soon........


Related posts
Continue Reading...

Add Hibernate javadoc to eclipse

Javadoc is a convenient way to learn and get help from documents which are provided by the programmer. These javadoc can be added to Eclipse IDE to view appropriate javadoc for a particular class or method or interface etc. These javadocs views on eclipse when auto complete (or content assist) appear. You can view the content assist by pressing 'Ctrl+Space'.

 
You can see the javadoc window on right hand side of this figure.

By default the javadoc for hibernate distribution does not exists. To add the javadoc to eclipse follow these steps.

Step 1
Download javadoc jar file from following link
hibernate-3.2.2.ga-javadoc.jar
Any how you should download the hibernate-3.2.2.ga-javadoc.jar file.

Step2 
Open eclipse and add above jar file to hibernate3.jar as a javadoc for it. To do that follow the steps explained below.

Step 3
Right click on 'hibernate3.jar' by expanding user library which contain all your hibernate reference jar files. And select 'Properties'.

Step 4
Select 'Javadoc Location' from side pane and click on 'Javadoc in archive' to select it.

Step 5
Browse for downloaded jar file and add that jar file location as javadoc location for 'hibernate3.jar'.

Step 6
Click 'Apply' and 'OK' to save the changes.


Now it is done you can view javadoc from eclipse.


Continue Reading...