Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Showing posts with label programs. Show all posts
Showing posts with label programs. Show all posts

Sunday, 28 July 2013

Simple Hibernate Example ..!

The files required to run the simple Hibernate Example.

1. Index.jsp
2. Web.xml
3. HibernateUtil.java
4. Person.java
5. hibernate.cfg.xml
6. Person.hbm.xml
7. server.xml

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
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="mypackage.*"%>
<%@ page import="org.hibernate.*"%>
<%@ page import="org.hibernate.cfg.*"%>
<HTML>
<HEAD>
<title>Greetings!</title>
</HEAD>
<BODY>
<%
org.hibernate.Session hibernateSession = mypackage.HibernateUtil.currentSession();
Transaction tx = hibernateSession.beginTransaction();

Person person = new Person();
person.setMyName("Joe");
hibernateSession.save(person);
tx.commit();
Query query = hibernateSession.createQuery("select p from Person as p where p.myName=:name");
query.setString("name", "Joe");
for (Iterator iter = query.iterate(); iter.hasNext() {
person = (Person) iter.next();
}
HibernateUtil.closeSession();
%>
<br>
<br>
<br>
<br>
<table width="400" border="0" cellspacing="1" cellpadding="0"
align="center" class="tableBox">
<tr>
<td CLASS="bluebanner" align="center">
Greetings,
<%=person.getMyName()%></TD>
</tr>
</table>
</BODY>
</HTML>


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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
The web.xml is:

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<display-name>hibernate</display-name>

<description>hibernate</description>

<!-- Servlets -->

<!-- Servlet Mappings -->


<!-- Session Expires in 1 day -->
<session-config>
<session-timeout>1440</session-timeout>
</session-config>

<!-- The Welcome File List -->
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>

<!-- Data Source References -->

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/hibernate</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

</web-app>

The Java source is in directory /WEB-INF/src:

package mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.out.println("Initial SessionFactory creation failed: " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}

public static final ThreadLocal hibernateSession = new ThreadLocal();

public static Session currentSession() {
Session s = (Session) hibernateSession.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
hibernateSession.set(s);
}
return s;
}

public static void closeSession() {
Session s = (Session) hibernateSession.get();
if (s != null)
s.close();
hibernateSession.set(null);
}
}

package mypackage;

public class Person {

private String myName;
private String id;

public String getId() {
return id;
}

private void setId(String id) {
this.id = id;
}


public String getMyName() {
return myName;
}

public void setMyName(String name) {
this.myName = name;
}
}

The hibernate.cfg.xml configuration files is:

<?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="connection.datasource">java:comp/env/jdbc/hibernate</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Mapping files -->
<mapping resource="Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

And the Person.hbm.xml file is:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="mypackage.Person" table="Person">

<!-- A 32 hex character is our surrogate key. It's automatically
generated by Hibernate with the UUID pattern. -->
<id name="id" type="string" unsaved-value="null" >
<column name="id" sql-type="char(32)" not-null="true"/>
<generator class="uuid.hex"/>
</id>

<!-- A cat has to have a name, but it shouldn' be too long. -->
<property name="myName">
<column name="name" length="80" not-null="true"/>
</property>

</class>

</hibernate-mapping>

The context xml for this example in Tomcat's server.xml is:


<Context path="/Hibernate" reloadable="true" docBase="C:\eclipse\workspace\Hibernate" workDir="C:\eclipse\workspace\hibernate\work">
<Resource name="jdbc/hibernate" scope="Shareable" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/hibernate">
<parameter>
<name>url</name>
<value>jdbc:mysql://127.0.0.1:3306/hibernate</value>
</parameter>

<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>2000</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
</ResourceParams>
</Context>

Good luck!

Friday, 26 July 2013

Hibernate – dynamic-update attribute example

What is dynamic-update ?


The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement.


Dynamic-update example



1. dynamic-update=false

The default value of dynamic-update is false, which means include unmodified properties in the Hibernate’s SQL update statement.
For example, get an object and try modify its value and update it.
Query q = session.createQuery("from StockTransaction where tranId = :tranId ");
q.setParameter("tranId", 11);
StockTransaction stockTran = (StockTransaction)q.list().get(0);
 
stockTran.setVolume(4000000L);
session.update(stockTran);
Hibernate will generate the following update SQL statement.
Hibernate: 
UPDATE
mkyong.stock_transaction
SET
DATE=?,
PRICE_CHANGE=?,
PRICE_CLOSE=?,
PRICE_OPEN=?,
STOCK_ID=?,
VOLUME=?
WHERE
TRAN_ID=?
Hibernate will update all the unmodified columns.

2. dynamic-update=true

If set the dynamic-insert to true, which means exclude unmodified properties in the Hibernate’s SQL update statement.
For example, get an object and try modify its value and update it again.
Query q = session.createQuery("from StockTransaction where tranId = :tranId ");
q.setParameter("tranId", 11);
StockTransaction stockTran = (StockTransaction)q.list().get(0);
 
stockTran.setVolume(4000000L);
session.update(stockTran);
Hibernate will generate different update SQL statement.
Hibernate: 
UPDATE
mkyong.stock_transaction
SET
VOLUME=?
WHERE
TRAN_ID=?
Hibernate will update the modified columns only.
Performance issue
In a large table with many columns (legacy design) or contains large data volumes, update some unmodified columns are absolutely unnecessary and great impact on the system performance.

How to configure it

You can configure “dynamic-update” properties via annotation or XML mapping file.

1. Annotation

@Entity
@Table(name = "stock_transaction", catalog = "mkyong")
@org.hibernate.annotations.Entity(
dynamicUpdate = true
)
public class StockTransaction implements java.io.Serializable {

2. XML mapping

<class ... table="stock_transaction" catalog="mkyong" dynamic-update="true">
<id name="tranId" type="java.lang.Integer">
<column name="TRAN_ID" />
<generator class="identity" />
</id>

Conclusion

This little “dynamic-update” tweak will definitely increase your system performance, and highly recommended to do it.


Wednesday, 24 July 2013

Finding the longest word in a user given string ..!

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
package com.kota.core;
import java.util.*;

class LongestWord {
String str = "Ram is intelligent boy";
String stringArray[] = str.split("\\s");

public String compare(String st1, String st2) {
if (st1.length() > st2.length()) {
return st1;
} else {
return st2;
}
}

LongestWord() {
String word = "";
for (int i = 0; i < stringArray.length; i++) {
if (i == 0) {
word = stringArray[0];
}
word = compare(word, stringArray[i]);
}
System.out.println("Longest word = " + word);
}

public static void main(String[] args) {
new LongestWord();
}
}
/**
* Out put : Longest word = intelligent
*
* */

Java - Overriding with code and explanation.

In the previous chapter we talked about super classes and sub classes. If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final.

The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means a subclass can implement a parent calss method based on its requirement.

In object oriented terms, overriding means to override the functionality of any existing method.

Example:

Let us look at an example.


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
package com.kota.core;

class Exp {
public int x = 3;

public void abc() {
x += 5;
System.out.println("the method of exp");
}

}

public class Exp1 extends Exp {
public int x = 8;

public Exp1(int y) {
x = y;
}

public void abc() {
x += 5;
System.out.println("the method of exp1");
}

public static void main(String[] rr) {

Exp b = new Exp1(10);
b.abc();
System.out.println("the value of=" + b.x);
}
}

/*Out put of the program:
* the method of exp1
* the value of=3
*
*
* */



Rules for method overriding:

The argument list should be exactly the same as that of the overridden method.

The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.

The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.

Instance methods can be overridden only if they are inherited by the subclass.

A method declared final cannot be overridden.

A method declared static cannot be overridden but can be re-declared.

If a method cannot be inherited then it cannot be overridden.

A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.

A subclass in a different package can only override the non-final methods declared public or protected.

An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

Constructors cannot be overridden.

how to find odd and even numbers in 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
/*
Even Odd Number Example
This Java Even Odd Number Example shows how to check if the given
number is even or odd.
*/

public class FindEvenOrOddNumber {

public static void main(String[] args) {

//create an array of 10 numbers
int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};

for(int i=0; i < numbers.length; i++){

/*
* use modulus operator to check if the number is even or odd.
* If we divide any number by 2 and reminder is 0 then the number is
* even, otherwise it is odd.
*/

if(numbers[i]%2 == 0)
System.out.println(numbers[i] + " is even number.");
else
System.out.println(numbers[i] + " is odd number.");

}

}
}

/*
Output of the program would be
1 is odd number.
2 is even number.
3 is odd number.
4 is even number.
5 is odd number.
6 is even number.
7 is odd number.
8 is even number.
9 is odd number.
10 is even number.

calculate factorial of a number using recursion in java

Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.

The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. for example, 3 factorial is 1×2×3, or 6. Here is how a factorial can be computed by use of a recursive method


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
class Factorial {

int fact(int n) {

int result;

if ( n ==1) return 1;

result = fact (n-1) * n;

return result;

}

}

class Recursion {

public static void main (String args[]) {

Factorial f =new Factorial();

System.out.println(“Factorial of 3 is “ + f.fact(3));

System.out.println(“Factorial of 3 is “ + f.fact(4));

System.out.println(“Factorial of 3 is “ + f.fact(5));

}

}

The output from this program is shown here:

Factorial of 3 is 6

Factorial of 4 is 24

Factorial of 5 is 120

If you are unfamiliar with recursive methods, then the operation of fact() may seem a bit confusing. Here is how it works. When fact() is called with an argument of 1, the function returns 1; otherwise it returns the product of fact(n-1)*n. to evaluate this expression, fact() is called with n-1. this process repeats until n equals 1 and the calls to the method begin returning.

To better understand how the fact() method works, let’s go through a short example. When you compute the factorial of 3, the first call to fact() will cause a second call to be made with an argument of 2. this invocation will cause fact() to be called a third time with an argument of 2. This call will return 1, which is then be called a third time with an argument of 1. This call will return1, which is then multiplied by 2 (the value of n in the second invocation). This result (which is 2) is then returned to the original invocation of fact() and multiply by 3 ( the original value of n). This yields the answer, 6. You might find it interesting to insert println() statements into fact() which will show at what level each call is and what the intermediate answers are.

When a method calls itself, new local variables and parameters are allocated storage on the stack, and the method code is executed with these new variables from the start. A recursive call does not make a new copy of the method. Only the arguments are new. As each recursive call returns, the old local variables and parameters are removed from the stack, and execution resumes at the point of the call inside the method. Recursive methods could be said to “telescope” out and back.

Recursive versions of many routines may execute a bit more slowly than the iterative equivalent because of the added overhead of the additional function calls. Many recursive calls to a method could cause a stack overrun. Because storage for parameters and local variables, it is possible that the stack could be exhausted. If this occurs, the java run-time system will cause an exception. However, you probably will not have to worry about this unless a recursive routine runs wild.

The main advantage to recursive methods is that they can be used to create clearer and simpler versions of several algorithms than can their iterative relatives. For example, the QuickSort sorting algorithm is quite difficult to implement in an iterative way.

Sunday, 14 July 2013

Get Sub Set from Java TreeSet example

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
/*
Get Sub Set from Java TreeSet example
This Java Example shows how to get the sub Set from Java TreeSet by giving specific
range of values using subSet method of Java TreeSet class.
*/

import java.util.TreeSet;
import java.util.SortedSet;

public class GetSubSetFromTreeSetExample {

public static void main(String[] args) {

// create TreeSet object
TreeSet tSet = new TreeSet();

// add elements to TreeSet
tSet.add("1");
tSet.add("3");
tSet.add("2");
tSet.add("5");
tSet.add("4");

/*
* To get the sub Set from Java TreeSet use, SortedSet subSet(int from,
* int to) method of TreeSet class.
*
* This method returns portion of the TreeSet whose elements range from
* from (inclusive) to to(exclusive).
*
* Please note that, the SortedSet returned by this method is backed by
* the original TreeSet. So any changes made to SortedSet will be
* reflected back to original TreeSet.
*/

SortedSet sortedSet = tSet.subSet("2", "5");

System.out.println("SortedSet Contains : " + sortedSet);

}
}

/*
* Output would be SortedSet Contains : [2, 3, 4]
*/

Iterate Over Unmodifiable Collection

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
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class UnmodifiableCollection {
/*
* Chandrasekhara Kota.
* */

public static void main(String args[]) {
List<String> list = new ArrayList<String>();

list.add("This");
list.add("is");
list.add("Unmodifiable Collection");

System.out.println("Element added to list: " + list.get(2));

Collection<String> immutableCol = Collections
.unmodifiableCollection(list);

Iterator<String> iterator = immutableCol.iterator();

while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

Friday, 12 July 2013

Replace all occurrences of specified element of Java ArrayList Example

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
import java.util.ArrayList;
import java.util.Collections;

public class ReplaceAllArrayListExample {

public static void main(String[] args) {

//create an ArrayList object
ArrayList arrayList = new ArrayList();

//Add elements to Arraylist
arrayList.add("A");
arrayList.add("B");
arrayList.add("A");
arrayList.add("C");
arrayList.add("D");

System.out.println("ArrayList Contains : " + arrayList);


Collections.replaceAll(arrayList, "A","Replace All");

System.out.println("After Replace All, ArrayList Contains : " + arrayList);
}
}

/*
Output would be
ArrayList Contains : [A, B, A, C, D]
After Replace All, ArrayList Contains : [Replace All, B, Replace All, C, D]
*/

Remove first and last elements of LinkedList Java example

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
import java.util.LinkedList;

public class RemoveFirstLastElementsLinkedListExample {

public static void main(String[] args) {

//create LinkedList object
LinkedList lList = new LinkedList();

//add elements to LinkedList
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");

System.out.println("LinkedList contains : " + lList);

Object object = lList.removeFirst();
System.out.println(object + " has been removed from the first index
of LinkedList");
System.out.println("LinkedList now contains : " + lList);

object = lList.removeLast();
System.out.println(object + " has been removed from the last index
of LinkedList");
System.out.println("LinkedList now contains : " + lList);

}
}

/*
Output would be

LinkedList contains : [1, 2, 3, 4, 5]
1 has been removed from the first index of LinkedList
LinkedList now contains : [2, 3, 4, 5]
5 has been removed from the last index of LinkedList
LinkedList now contains : [2, 3, 4]
*/

LinkWithin

Related Posts Plugin for WordPress, Blogger...