Facebook Photo Album Java Application

21 Mar

Here is the first version(1.0.0) of Facebook Photo Album Application which is made in Java.

Click on Share button if you like this Application.

Enjoy!!!

Click Here to Launch Application or Click on below image.

OrmLite Example in Android

20 Dec

1) Create New Project with name “OrmLiteAndroid”

2) add two libraries file in project

ormlite-core-4.28.jar
ormlite-android-4.28.jar

3) Create Entity class with Default Constructor (with @DatabaseField annotation)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class Person {
 
	@DatabaseField(generatedId = true)
	int id;
	@DatabaseField
	String firstname;
	@DatabaseField
	String lastname;
	@DatabaseField
	int age;
	@DatabaseField
	int salary;
 
	Person() {
 
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getFirstname() {
		return firstname;
	}
 
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
 
	public String getLastname() {
		return lastname;
	}
 
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
 
	public int getAge() {
		return age;
	}
 
	public void setAge(int age) {
		this.age = age;
	}
 
	public int getSalary() {
		return salary;
	}
 
	public void setSalary(int salary) {
		this.salary = salary;
	}
}

4) Create Database Helper Class with name “DatabaseHelper.java”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.sql.SQLException;
import java.util.List;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
 
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
 
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
 
	private Context _context;
	private static final String DATABASE_NAME = "ormliteandroid.db";
	private static final int DATABASE_VERSION = 1;
 
	private Dao<Person, String> simpleDao = null;
	private RuntimeExceptionDao<Person, String> simpleRuntimeDao = null;
 
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		_context = context;
	}
 
	public Dao<Person, String> getDao() throws SQLException {
		if (simpleDao == null) {
			simpleDao = getDao(Person.class);
		}
		return simpleDao;
	}
 
	public RuntimeExceptionDao<Person, String> getSimpleDataDao() {
		if (simpleRuntimeDao == null) {
			simpleRuntimeDao = getRuntimeExceptionDao(Person.class);
		}
		return simpleRuntimeDao;
	}
 
	//method for list of person
	public List<Person> GetData()
	{
		DatabaseHelper helper = new DatabaseHelper(_context);
		RuntimeExceptionDao<Person, String> simpleDao = helper.getSimpleDataDao();
		List<Person> list = simpleDao.queryForAll();
		return list;
	}
 
	//method for insert data
	public int addData(Person person)
	{
		RuntimeExceptionDao<Person, String> dao = getSimpleDataDao();
		int i = dao.create(person);
		return i;
	}
 
	//method for delete all rows
	public void deleteAll()
	{
		RuntimeExceptionDao<Person, String> dao = getSimpleDataDao();
		List<Person> list = dao.queryForAll();
		dao.delete(list);
	}
 
	@Override
	public void close() {
		super.close();
		simpleRuntimeDao = null;
	}
 
	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onCreate");
			TableUtils.createTable(connectionSource, Person.class);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
			throw new RuntimeException(e);
		}
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		try {
			Log.i(DatabaseHelper.class.getName(), "onUpgrade");
			TableUtils.dropTable(connectionSource, Person.class, true);
			onCreate(db, connectionSource);
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
			throw new RuntimeException(e);
		}
	}
}

5) Here is the code for Insert, List and Delete data

Code for Insert Data in Database:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Person person = new Person();
person.setFirstname(Enter first name here);
person.setLastname(enter last name here);
person.setAge(Integer.parseInt(enter age here));
person.setSalary(Integer.parseInt(enter salary here));
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
<strong>int i = helper.addData(person);</strong>
if(i&gt;0)
{
Toast.makeText(getBaseContext(), "Data Successfully Added", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Error Occured", Toast.LENGTH_SHORT).show();
}

Code for List of All Person from Database:

1
2
3
4
5
6
7
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
List&lt;Person&gt; list = helper.GetData();
content.setText("");
for(Person person:list)
{
content.append(person.getId()+"  "+person.getFirstname()+"  "+person.getLastname()+"  "+person.getAge()+"  "+person.getSalary()+"\n");
}

Code for Delete all Entries from Database:

1
2
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
helper.deleteAll();

notifyDataSetChanged() in Android

19 Dec

This tutorial is for notifyDataSetChanged() method in android application. this method helps you to Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

1) Create New Project with name “NotifyDemo”

2) Change main.xml file code with below code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="410dp"
        android:layout_weight="0.68"
        android:cacheColorHint="#00000000" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.65"
        android:text="Button" />
</LinearLayout>

3) now create “listdetails.xml” in layout folder for list element layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
 
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="42dp"
            android:text="First Name"
            android:textAppearance="?android:attr/textAppearanceLarge" />
 
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="32dp"
            android:text="Last Name"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </RelativeLayout>
 
</LinearLayout>

4) now create one Person.java class as business object to simplify list data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Person {
 
	private String fname;
	private String lname;
 
	public String getFname() {
		return fname;
	}
	public void setFname(String fname) {
		this.fname = fname;
	}
	public String getLname() {
		return lname;
	}
	public void setLname(String lname) {
		this.lname = lname;
	}
}

5) Here is your final NotifyDemoActivity.java Activity code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.ArrayList;
import java.util.List;
 
import android.app.Activity;
import android.content.Context;
 
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.view.ViewGroup;
 
public class NotifyDemoActivity extends Activity {
 
	 private LayoutInflater mInflater;
	 ArrayAdapter&lt;Person&gt; adapter;
	 ListView listView;
	 ViewHolder holder;
	 List&lt;Person&gt; list;
	 String appId;
 
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
 
       //initialize your array
       list = new ArrayList&lt;Person&gt;();
 
       Person person1 = new Person();
       person1.setFname("Anand");
       person1.setLname("Gajjar");
       list.add(person1);
 
       Person person2 = new Person();
       person2.setFname("Tirthesh");
       person2.setLname("Ganatra");
       list.add(person2);
 
       Button button = (Button)findViewById(R.id.button1);
       button.setOnClickListener(new View.OnClickListener() {
 
			@Override
			public void onClick(View v) {
 
				Person person = new Person();
		        person.setFname("Fname");
		        person.setLname("Lname");
		        list.add(person);
		        adapter.notifyDataSetChanged();
			}
		});
 
       mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		listView = (ListView)findViewById(android.R.id.list);
		adapter = new ArrayAdapter&lt;Person&gt;(NotifyDemoActivity.this, R.layout.listdetails, list)
		{
		  			    		@Override
	    						    public View getView(final int position, View convertView, ViewGroup parent)
	    						    {
 
	    						        		if (null == convertView)
	    						        		{
   						        			convertView = mInflater.inflate(R.layout.listdetails, parent, false);
 
	    						        		holder = new ViewHolder();
	    						        		holder.fname = (TextView)convertView.findViewById(R.id.textView1);
	    						        		holder.lname = (TextView)convertView.findViewById(R.id.textView2);
	    						        		convertView.setTag(holder);
	    						        		}
	    						        		else
	    						        		{
	    						        		holder = (ViewHolder) convertView.getTag();
	    						        		}
	    						        		holder.fname.setText(list.get(position).getFname());
	    						        		holder.lname.setText(list.get(position).getLname());
 
	    						        		return convertView;
	    						    }
	    	};
	    	listView.setAdapter(adapter);
   }
 
   static class ViewHolder
	   {
		   private TextView fname;
		   private TextView lname;
	   }
}

 

output:


1) the first screen is default screen with two entries.
NotifyDemo output
2) when you click on Button. it will add one more entry in list and update adapter with notifyDataSetChanged(); method.
NotifyDemo output

ViewFlipper in android

19 Dec

1) Create New Project with name “ViewFlipperDemo”

2) Change main.xml code with below code.

<?xml version="1.0" encoding="utf-8"?>
 
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
 
<LinearLayout android:id="@+id/LinearLayout03"
android:layout_width="wrap_content" android:layout_height="wrap_content">
</LinearLayout>
 
<LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="fill_parent">
 
<ViewFlipper
android:id="@+id/ViewFlipper01"
android:layout_width="fill_parent" android:layout_height="fill_parent">
</ViewFlipper>
 
</LinearLayout>
</LinearLayout>

3) Create one ListData.java class with one method which give you a number of content for your Screen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class ListData {
 
	public List&lt;String&gt; getList()
	{
		List&lt;String&gt; list = new ArrayList&lt;String&gt;();
		list.add("Person1");
		list.add("Person2");
		list.add("Person3");
		list.add("Person4");
		list.add("Person5");
		list.add("Person6");
		list.add("Person7");
		list.add("Person8");
		list.add("Person9");
		return list;
	}
 
}

4) Create one layout.xml file for to display ViewFlipper screen data

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/layout1">
 
    <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/relativeLayout1">
        <TextView android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_marginLeft="14dp" android:layout_marginTop="32dp"></TextView>
        <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText1" android:layout_alignBottom="@+id/textView1" android:layout_toRightOf="@+id/textView1" android:layout_marginLeft="21dp" android:layout_alignParentRight="true"></EditText>
        <Button android:onClick="onClick" android:text="Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button1" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true"></Button>
    </RelativeLayout>
 
</LinearLayout>

5) now your require four different animation file to translate your screen from one to another.

you can download this four file from here.
slide_out_left.xml
slide_out_left2.xml
slide_in_right.xml
slide_in_right2.xml

6) now add below code in ViewFlipperDemoActivity.java Class

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import java.util.List;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
 
public class ViewFlipperDemoActivity extends Activity implements OnClickListener{
	Button next;
	Button previous;
	ViewFlipper vf;
	EditText editText;
	Button button;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
 
		ListData listData = new ListData();
		List&lt;String&gt; items = listData.getList(); 
 
		vf = (ViewFlipper) findViewById(R.id.ViewFlipper01);
		final Animation s_in  = AnimationUtils.loadAnimation(this, R.drawable.slide_in_right);
		final Animation s_out = AnimationUtils.loadAnimation(this, R.drawable.slide_out_left);
		final Animation s_in2  = AnimationUtils.loadAnimation(this, R.drawable.slide_in_right2);
		final Animation s_out2 = AnimationUtils.loadAnimation(this, R.drawable.slide_out_left2);
 
		for (String item : items) {
			LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View contentView = mInflater.inflate(R.layout.layout, null , false);
			button = (Button)findViewById(R.id.button1);
			editText = (EditText)findViewById(R.id.editText1);
			TextView textView1= (TextView)contentView.findViewById(R.id.textView1);
			textView1.setText(""+item);
			this.vf.addView(contentView);
		}
 
 
		this.vf.setOnTouchListener(new View.OnTouchListener() {
 
			float downXValue = 0;
			long downTime = 0;
 
			@Override
			public boolean onTouch(View view, MotionEvent event) {
 
				switch (event.getAction()) {
 
				case MotionEvent.ACTION_DOWN:
				{
					downXValue = event.getX();
					Log.i("Touch Down:",  "Down: " + downXValue);
					downTime = event.getEventTime();
					break;
				}
 
				case MotionEvent.ACTION_UP:
				{
					float currentX = event.getX();
					long currentTime = event.getEventTime();
					float difference = Math.abs(downXValue - currentX);
					long time = currentTime - downTime;
 
					Log.i("Touch Event:",  "Distance: " + difference + "px Time: " + time + "ms");
 
					if ( (downXValue &lt; currentX) &amp;&amp; (time &gt; 50) &amp;&amp; (difference &gt; 50) ) {
						vf.setInAnimation(s_in);
						vf.setOutAnimation(s_out);
						vf.showPrevious();
					}
 
					if ( (downXValue &gt; currentX) &amp;&amp; (time &gt; 50) &amp;&amp; (difference &gt; 50) ) {
						vf.setInAnimation(s_in2);
						vf.setOutAnimation(s_out2);
						vf.showNext();
					}
					break;
				}
				}
				return true;
			}
		});
	}
 
	@Override
	public void onClick(View v) {
		v = vf.getCurrentView();
		EditText editText = (EditText)v.findViewById(R.id.editText1);
		Toast.makeText(getBaseContext(), ""+editText.getText().toString(), Toast.LENGTH_SHORT).show();
	}
}

Custom Title bar in Android

27 Nov

Create New Android Project in eclipse with name “CustomTitlebarActivity”.
here is your main Activity Code.
CustomTitlebarActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import android.app.Activity;
 
import android.os.Bundle;
import android.view.Window;
 
public class CustomTitlebarActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custome_title);
    }
}

set custom theme property in you activity tag.
here is yout modified AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.titile.ui"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="8" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".CustomTitlebarActivityActivity" android:theme="@style/CustomTheme">
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

create custom_style.xml in res/values folder. and copy this code in custom_style.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
     <style name="CustomWindowTitleBackground">
        <item name="android:background">#323331</item>
    </style>
 
    <style name="CustomTheme" parent="android:Theme">
        <item name="android:windowTitleSize">50dp</item>
        <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
    </style>
 
</resources>

now customize your title bar with this xml file. here i added one Button and one Textview in title bar.
you can modify this file according to requirement.
custome_title.xml file

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/relativeLayout1"
	android:layout_width="fill_parent"
	android:background="#005BAA"
	android:layout_height="50dp">
 
    <Button
    android:layout_centerVertical="true"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:text="Button"
    android:id="@+id/button1"
    android:layout_alignParentRight="true"
    android:layout_marginRight="7dp"  >
    </Button>
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:text="Title Content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@android:color/black" />
</RelativeLayout>

finally here is your main.xml file with simple textview on screen.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Example of Custom Title bar" />
</LinearLayout>

output

custom title bar output

Custom Progress bar in Android

27 Nov

first create new project in eclipse and change your main.xml code. here is your new code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
 
        <ProgressBar
            android:id="@+id/progressBar1"
             android:indeterminateDrawable="@drawable/progressbackground1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="20dp" />
 
        <ProgressBar
            android:id="@+id/progressBar2"
             android:indeterminateDrawable="@drawable/progressbackground2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="150dp"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>
 
</LinearLayout>

 

and then create new XML file in drawable folder with progressbackground1.xml. and copy below code in this new XML.

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/progressbar1"
android:pivotX="50%"
android:pivotY="50%" />

 

again create new XML file for second custom progress bar with name progressbackground2.xml. and copy below code in it.

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/progressbar2"
android:pivotX="50%"
android:pivotY="50%" />

here is your new progress bar custom image. save this two png file in your drawable folder of android project.

progressbar image
progressbar image

output

custom progressbar image output

One to Many relationship in Hibernate

26 Nov

One to Many relationships

The One to Many relationship is the most commonly used relationship of all kind. Below given example is of the user and policies he can invest in i.e., a single user can invest in many polices.

The relation ship is b/w the two tables are as shown in the figure below:

one2one_relationship

In one to one relationship the key in the one table is common in the other table with which it is linked to. In the above example we have user_id key in the user_main table where it is the foreign key in the user_detail table and act as a primary key as well.

HibernateMapping

There are two java classes:

User.java —> user_main table

Policy.java —> policy_main table

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.HashSet;
import java.util.Set;
 
public class User {
 
	private int id;
	private String userName;
	private String password;
	private Set&lt;Policy&gt; userPolicies = new HashSet&lt;Policy&gt;();
 
	public User() {
	}
 
	public User(String userName, String password){
		this.userName = userName;
		this.password = password;
	}
 
	public User(String userName, String password, Set&lt;Policy&gt; policies){
		this.userName = userName;
		this.password = password;
		this.userPolicies = policies;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getUserName() {
		return userName;
	}
 
	public void setUserName(String userName) {
		this.userName = userName;
	}
 
	public String getPassword() {
		return password;
	}
 
	public void setPassword(String password) {
		this.password = password;
	}
 
	public Set&lt;Policy&gt; getUserPolicies() {
		return userPolicies;
	}
 
	public void setUserPolicies(Set&lt;Policy&gt; userPolicies) {
		this.userPolicies = userPolicies;
	}
 
}

UserDetails.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.Serializable;
import java.util.Date;
 
public class Policy {
 
	private int policyId;
	private float policyAmount;
	private Date policyRegDate;
	private Date policyMatureDate;
	private User user;
 
	public int getPolicyId() {
		return policyId;
	}
 
	public void setPolicyId(int policyId) {
		this.policyId = policyId;
	}
 
	public float getPolicyAmount() {
		return policyAmount;
	}
 
	public void setPolicyAmount(float policyAmount) {
		this.policyAmount = policyAmount;
	}
 
	public Date getPolicyRegDate() {
		return policyRegDate;
	}
 
	public void setPolicyRegDate(Date policyRegDate) {
		this.policyRegDate = policyRegDate;
	}
 
	public Date getPolicyMatureDate() {
		return policyMatureDate;
	}
 
	public void setPolicyMatureDate(Date policyMatureDate) {
		this.policyMatureDate = policyMatureDate;
	}
 
	public User getUser() {
		return user;
	}
 
	public void setUser(User user) {
		this.user = user;
	}
}

user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
 
<hibernate-mapping>
 
	<class name="com.ttw.hibernate.vo.User" table="user_main" lazy="false">
 
		<id name="id" column="user_id" type="java.lang.Integer">
			<generator class="identity" />
		</id>
 
        <property name="userName" type="string">
            <column name="user_name" length="20" not-null="true" unique="true" />
        </property>
 
        <property name="password" type="string">
            <column name="password" length="20" not-null="true"/>
        </property>
 
        <set name="userPolicies" inverse="true" lazy="true" table="policy_main" fetch="select">
            <key>
                <column name="user_id" not-null="true" />
            </key>
            <one-to-many class="com.ttw.hibernate.vo.Policy" />
        </set>
 
	</class>
</hibernate-mapping>

policy.hbm.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
 
 <hibernate-mapping>
 <class name="com.ttw.hibernate.vo.Policy" table="policy_main" >
        <id name="policyId" type="java.lang.Integer">
            <column name="policy_id" />
            <generator class="identity" />
        </id>
 
        <many-to-one name="user" class="com.ttw.hibernate.vo.User" fetch="select">
            <column name="user_id" not-null="true" />
        </many-to-one>
 
        <property name="policyAmount" type="java.lang.Float">
            <column name="policy_amt" precision="6" />
        </property>
 
		<property name="policyRegDate" type="date">
            <column name="policy_reg_date" length="10" not-null="true" unique="true" />
        </property>
 
		<property name="policyMatureDate" type="date">
            <column name="policy_mat_date" length="10" not-null="true" unique="true" />
        </property>
 
    </class>
 </hibernate-mapping>

Testing.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.Date;
 
import org.hibernate.Session;
 
import com.ttw.hibernate.util.HibernateUtil;
import com.ttw.hibernate.vo.Policy;
import com.ttw.hibernate.vo.User;
 
public class Testing {
 
	public static void main(String[] args) {
 
		Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
		session.getTransaction().begin();
 
		User user = new User("thetransientway", "thetransientway");
		Policy policy = new Policy();
 
		policy.setPolicyAmount(49000);
		policy.setPolicyRegDate(new Date());
		policy.setPolicyMatureDate(new Date());
 
		policy.setUser(user);
		user.getUserPolicies().add(policy);
 
		session.save(user);
		session.save(policy);
 
		session.getTransaction().commit();
		session.close();
	}
 
}

output

output

 

One to One relationship in Hibernate

26 Nov

One to One relationships

According to Mike Chapple One-to-one relationships occur when there is exactly one record in the first table that corresponds to exactly one record in the related table. Here in this turorial we are taking an example user_main and user_detail tables.

The relation ship is like as shown in the figure below:

one2one_relationship

In one to one relationship the key in the one table is common in the other table with which it is linked to. In the above example we have user_id key in the user_main table where it is the foreign key in the user_detail table and act as a primary key as well.

Hibernate Mapping

There are two java classes:

User.java —> user_main table

UserDetails.java —> user_details table

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class User{
 
	private int id;
	private String userName;
	private String password;
	private UserDetails userDetails;
 
	public User() {
	}
 
	public User(String userName, String password){
		this.userName = userName;
		this.password = password;
	}
 
	public User(String userName, String password, UserDetails userDetails){
		this.userName = userName;
		this.password = password;
		this.userDetails = userDetails;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getUserName() {
		return userName;
	}
 
	public void setUserName(String userName) {
		this.userName = userName;
	}
 
	public String getPassword() {
		return password;
	}
 
	public void setPassword(String password) {
		this.password = password;
	}
 
	public UserDetails getUserDetails() {
		return userDetails;
	}
 
	public void setUserDetails(UserDetails userDetails) {
		this.userDetails = userDetails;
	}
}

 

UserDetails.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class UserDetails {
 
	private int id;
	private String userAddress;
	private long phoneNumber;
	private User user;
 
	public UserDetails() {
	}
 
	public UserDetails(String userAddress, long phoneNumber, User user){
		this.phoneNumber = phoneNumber;
		this.userAddress = userAddress;
		this.user = user;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getUserAddress() {
		return userAddress;
	}
 
	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}
 
	public long getPhoneNumber() {
		return phoneNumber;
	}
 
	public void setPhoneNumber(long phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
 
	public User getUser() {
		return user;
	}
 
	public void setUser(User user) {
		this.user = user;
	}
}

onetoone.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
 
	<class name="com.ttw.hibernate.vo.User" table="user_main" lazy="false">
 
		<id name="id" column="user_id" type="java.lang.Integer">
			<generator class="identity" />
		</id>
 
        <property name="userName" type="string">
            <column name="user_name" length="20" not-null="true" unique="true" />
        </property>
 
        <property name="password" type="string">
            <column name="password" length="20" not-null="true"/>
        </property>
 
        <one-to-one name="userDetails" class="com.ttw.hibernate.vo.UserDetails" cascade="save-update"></one-to-one>
	</class>
 
	<class name="com.ttw.hibernate.vo.UserDetails" table="user_details" >
        <id name="id" type="java.lang.Integer">
            <column name="user_id" />
            <generator class="foreign">
                <param name="property">user</param>
            </generator>
        </id>
 
        <one-to-one name="user" class="com.ttw.hibernate.vo.User" constrained="true"></one-to-one>
 
        <property name="userAddress" type="string">
            <column name="user_address" length="100" not-null="true" />
        </property>
 
        <property name="phoneNumber" type="java.lang.Long">
            <column name="user_phno" />
        </property>
    </class>
 
</hibernate-mapping>

Testing.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import org.hibernate.Session;
 
import com.ttw.hibernate.util.HibernateUtil;
import com.ttw.hibernate.vo.User;
import com.ttw.hibernate.vo.UserDetails;
 
public class Testing {
 
	public static void main(String[] args) {
		Session session = HibernateUtil.getInstance().getSessionFactory().openSession();
                session.beginTransaction();
 
		User user = new User("tganatra", "tganatra");
		UserDetails userDetails = new UserDetails("ahmedabad 15", 9800100, user);
 
		user.setUserDetails(userDetails);
 
		session.save(user);
        session.getTransaction().commit();
	}
}

output

o2o_hbm_file

 

Introduction to Hibernate

26 Nov

Hibernate Basic

What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and Persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.
Hibernate solves object-relational impedance mismatchproblems by replacing direct persistence-related database accesses with high-level object handling functions.
Hibernate 3.0, the Open Source persistence technology at the heart of J2EE EJB 3.0 is available for download from Hibernet.org.The Hibernate 3.0 core is 68,549 lines of Java code together with 27,948 lines of unit tests, all freely available under the LGPL, and has been in development for well over a year.

Goal of Hibernate.

Hibernate 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.
To provide automated & optimized techniques.
To reduce the time that developers devote to manual coding & make them concentrated more on business    logic of their application (25%).
To provide smart fetching & cashing.
To supply a toolset for development.
Automatic Key Generation: Hibernate supports the automatic generation of primary key for your.
Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.

JDBC Vs Hibernate

 

Relational Persistence for JAVA
Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model’s data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

Transparent Persistence
The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

Support for Query Language
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

Database Dependent Code
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

Maintenance Cost
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

Optimize Performance
Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many
times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching is maintained by hand-coding.

 

 

Disadvantages of Hibernate

Steep learning curve.

Use of Hibernate is an overhead for the applications which are :

  • simple and use one database that never change.
  • need to put data to database tables, no further SQL queries.
  • there are no objects which are mapped to two different tables. Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.

 

Support for Hibernate on Internet is not sufficient.

Anybody wanting to maintain application using Hibernate will need to know Hibernate.

For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.

Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.

 

 

Architecture of Hibernate

26 Nov

Architecture of Hibernate 3.0

Hibernate is built on top of many Java APIs and other Java open source frameworks/APIs. The architecture is layered to keep you isolated from having to know the underlying APIs. In fact, while the available Hibernate API is large, the API used by most application developers is relatively small. One only needs to know fewer than a dozen Hibernate classes to use Hibernate.

hibernate architecture

The Configuration object, as seen in the example code, is the first Hibernate object you use. It represents a configuration or properties file for Hibernate. The Configuration object is usually created once during application initialization. The Configuration object reads and establishes the properties Hibernate uses to get connected to a database and configure itself for work. A Configuration object is used to create a SessionFactory and then typically is discarded.

The SessionFactory is created from a Configuration object, and as its name implies it is a factory for Session objects.

The SessionFactory is an expensive object to create. It, like the Configuration object, is usually created during application start up. However, unlike the Configuration object, It should be created once and kept for later use.

The SessionFactory object is used by all the threads of an application. It is a thread safe object. One SessionFactory object is created per database. Multiple SessionFactory objects (each requiring a separate Configuration) are created when connecting to multiple databases. The SessionFactory can also provide caching of persistent objects.

hibernate architecture

Session objects provide the main interface to accomplish work with the database. Persistent objects are saved and retrieved through a Session object. A Session object is lightweight and inexpensive to create. A Session object does the work of getting a physical connection to the database. Session objects maintain a cache for a single application thread (request).

Session objects are not thread safe. Therefore, session objects should not be kept open for a long time. Applications create and destroy these as needed. Typically, they are created to complete a single unit of work, but may span many units.

When modifications are made to the database, Session objects are used to create a Transaction object. A Transaction represents a unit of work with the database (and potentially other systems). Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC, JTA or CORBA). Hibernate with use whatever transaction implementation is available (JDBC, JTA, CORBA, etc.). The Hibernate Transaction object abstracts the developer from having to deal with the underlying transaction manager/transaction. This allows developers to use a Transaction Manager of their choice without having to code to a specific Transaction Manager. Transaction objects should be kept open for as short of time as possible. There will be more information on Transactions and Transaction Management in a later chapter in class.

Query and Criteria objects are used to retrieve (and recreate) persistent objects. Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. Criteria uses an object/method based means of constructing and executing a request to retrieve objects. Query and Criteria will also be covered in a later chapter in class.