Sunday 29 December 2013

How to Connect Java With Mysql in eclipse

Step 1: Download mysql Connector from the link Below.

http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.0.8/mysql-connector-java-5.0.8.jar

Step2: Right Click on project name select properties, then select java Build Path and go to Libraries tab.

Step 3: Click  on add External jar browse to the downloaded mysql-connector jar file then Click ok.
Step 4:  write the following code.

import java.sql.*;

public class ConnectToMySql {
   
    public static void main(String[] args) throws Exception {
   
       Class.forName("com.mysql.jdbc.Driver"); //checking for drivers
//DriverManager.getConnection("jdbc:mysql://servername/database","username","password")
       Connection con =  DriverManager.getConnection("jdbc:mysql://localhost/test","root","");

       Statement st=con.createStatement();
       System.out.println("Connected To MySql 5.0");
       ResultSet rs=st.executeQuery("SELECT * FROM users"); //users table name
       while ( rs.next()) {
           System.out.println( rs.getString("username") + ":" + rs.getString("password"));//username and password are the fields of users table
       }
       con.close();
    }
}

Tuesday 24 December 2013

Creating a Client Proxy in Java

@WebServiceClient(name = "CalculatorWSService", 
targetNamespace = "http://calculator.me.org/", 
wsdlLocation = "http://localhost:4933/CalculatorApp/CalculatorWSService?wsdl")
public class CalculatorWSService extends Service { //...
@WebEndpoint(name = "CalculatorWSPort")
public CalculatorWS getCalculatorWSPort() {
return super.getPort(new QName("http://calculator.me.org/", 
"CalculatorWSPort"), CalculatorWS.class);
}

Here  the  getCalculatorWSPort method  returns  an  object  that  implements  the
CalculatorWSinterface, which is discussed next. The no-arg  getPortmethod can be
used  in  general;  the  second  getPort method  accepts  a  variable-length  array  of
javax.xml.ws.WebServiceFeatureobjects that can be used by clients to configure certain
aspects of the invocation, such as whether to enable MTOM or WS-Addressing.


In the calculator example, the port has one method, to match the single addoperation
defined in the WSDL. Let’s take a step back and unpack this for a moment, as there’s
a lot going on here:
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "add", 
targetNamespace = "http://calculator.me.org/", 
className = "org.me.calculator.Add")
@ResponseWrapper(localName = "addResponse", 
targetNamespace = "http://calculator.me.org/", 
className = "org.me.calculator.AddResponse")
public int add(
@WebParam(name = "i", targetNamespace = "")
int i,
@WebParam(name = "j", targetNamespace = "")
int j);

As you can see, your seemingly simple, innocuous addmethod suddenly has a variety

of annotations adorning it. We’ll account for these one by one.
First, your WSDL specifies the following in the messages section:
<message name="add"> <part name="parameters" element="tns:add"></part> </message>
So the SEI needs to account for this message, and creates an annotation indicating that
the runtime will create a message with a QNamethat contains a local part of add, in the
specified  namespace. That message is derived from the Java class that is also generated,
org.me.calculator.Add, which looks like this:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "add", propOrder = {
"i",
"j"
})
public class Add {
protected int i;
protected int j;
//getters and setters omitted
That class acts as the wrapper for each of the integers that will be sent in the request.
The @Xml annotations on this class come from JAXB. They indicate how JAXB should
marshal and unmarshal instances of this class to and from XML. The @XmlTypeannotation is used to specify that this  Addclass matches a top-level complex type (or an
enum) within an XML schema, and the “name” property is specified as “add” in it, to
match the item’s name within the schema. If you look at the schema that your WSDL
refers to, you see the following complex type, which matches your Addclass:
<xs:complexType name="add">
<xs:sequence>
<xs:element name="i" type="xs:int"></xs:element>
<xs:element name="j" type="xs:int"></xs:element>
</xs:sequence>
</xs:complexType>
But why does this type get created for you? Integers are defined as basic types provided
with XML Schema; they are not custom types that you have written that require something special. The complex type that wraps these two integers is created in order to
match your WSDL, which uses the document/literal style. Here is the portion of the
WSDL that tells you this:
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" 
style="document"></soap:binding>
<operation name="add">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal"></soap:body>
</input>
Had you been using RPC and not document, the values would have been passed separately to the operation invocation just like method parameters.

The  @RequestWrapperand  @ResponseWrapperannotations capture information that JAXB
needs to perform the marshaling and unmarshaling operations. If your service is defined
as using document/literal mode, as ours is, this annotation also serves to resolve overloading conflicts.
Now, let’s write a quick program to invoke the generated client code and get a result
from your service. Here are the steps in their simplest form, stripped of any unnecessary
items so you can get the clearest picture.

import org.me.calculator.*;

public class CalculatorInvoker {
public static void main(String... arg) {
CalculatorWSService service = new CalculatorWSService();
CalculatorWS port = service.getCalculatorWSPort();
int result = port.add(2, 3);
System.out.println("Result: " + result);
}
}

Then you can run it:
>java -cp . CalculatorInvoker
Result: 5



Invoking the Simplest Web Service In Java

import java.net.URL;
import java.util.Iterator;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class HelloClient {
public static void main(String[] args) throws Exception {
//Specify the WSDL 
//Create a Qualified Name that represents the 
//namespace and local part of the service
QName serviceName = new QName("http://ch03.soacookbook.com/", 
"HelloWSService");
//Create a proxy to get a port stub from
Service service = Service.create(wsdlLocation, serviceName);
// Return a list of QNames of ports
System.out.println("QNames of service endpoints:");
Iterator<QName> it = service.getPorts();
QName lastEndpoint = null;
while (it.hasNext()) {
lastEndpoint = it.next();
System.out.println("Name: " + lastEndpoint);
//prints: Name: {http://ch03.soacookbook.com/}HelloWSPort
}
// Get the Hello stub
Hello hello = service.getPort(lastEndpoint, Hello.class);
//Invoke the business method
String result = hello.sayHello("Duke");
System.out.println("\nResponse: " + result);
}
}

ITERATORS in C++

Iterators are similar to pointers in that they point to elements in a container. Iterators
are commonly used in C++ and are very important when using the STL.
 A number of functions dealt with iterators, and in the following section we will
take a closer look at them and how they relate to the vector template class.

#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
using namespace std;
void PrintVector(vector<int> &array)
{

cout << "Contents (" << "Size: " << (int)array.size() <<
" Max: " << (int)array.capacity() << ") - ";
ostream_iterator<int> output(cout, " ");
copy(array.begin(), array.end(), output);
cout << endl;
}
int main(int args, char **argc)
{
cout << "STL Vector Example 2: Iterators" << endl;
cout << "Data Structures for Game Developers" << endl;
cout << "Allen Sherrod" << endl << endl;
vector<int> array;
array.reserve(5);
// Add items then print.
array.push_back(10);
array.push_back(20);
array.push_back(30);
array.push_back(40);
array.push_back(50);
// Calling the copy algorithm.
vector<int> array2;
for(int i = 0; i < 5; i++)
array2.push_back(0);
copy(array.begin(), array.end(), array2.begin());
cout << " Inserted into vector: ";
PrintVector(array);
// Run the accumulate algorithm.
cout << " Accumulate: "
<< accumulate(array.begin(), array.end(), 0)
<< endl;
// Pop off the container.
array.pop_back();
array.pop_back();
cout << "Popped two from vector: ";
PrintVector(array);
// Clear the container.
array.clear();
cout << " Cleared vector: ";
PrintVector(array);
cout << endl;
// Test if the container is empty.
if(array.empty() == true)
cout << "Vector is empty.";
else
cout << "Vector is NOT empty.";
cout << endl << endl;
return 1;
}
the demo application stlvector in Listing  Vector Demo by creating an integer container and
filling it with elements. Once the container is filled, the STL copy algorithm is used
to copy the first container into another. Before the copying, a loop is used to create
the element space in the second container because to copy the first container into
the second, the second must have at least the number of elements required by the
range, which is specified by the iterators begin(first element or [0]) and end(last
element or [4]in this case).
After the copy algorithm is performed and the container is displayed, the
accumulate STL algorithm is performed to demonstrate that to get the sum of all
the elements, a few pop()calls are performed, the container is cleared, and it is
tested for emptiness. Inside the function used to print the container is new code
that replaces the forloop in the first vectordemo application stlvector. In this
function an output iterator is created and the STL copy algorithm is called. The call
states that the range of elements from the first parameter (the beginning of the container in this case) to the second parameter (the end of the container in this case)
should be copied to the output iterator. The output iterator for this demo application is set up to point to the C++ STD count object. This is an example of how to use
algorithms and iterators together to perform fast tasks in C++ code. Using a for
loop is one option, which was seen in the first stl vector demo, but it is slower than
using STL algorithms. Whenever possible use STL algorithms for traditional arrays
and containers because the performance is efficient. The output iterator that is set
up in points to the coutobject and appends a ""character to every
element that is passed to it. This is what gives the output a space between each
element that is printed

C++ Vector Demo

#include<iostream>
#include<vector>
using namespace std;
void PrintVector(vector
&array)
{
cout << "Contents (" << "Size: " << (int)array.size() <<
" Max: " << (int)array.capacity() << ") - ";
for(int i = 0; i < (int)array.size(); i++)
{
cout << array[i] << " ";
}
cout << endl;
}

int main(int args, char **argc)
{
cout << "STL Vector Example" << endl;
cout << "Data Structures for Game Developers" << endl;
cout << "Allen Sherrod" << endl << endl;
vector
array;
array.reserve(5);
array.push_back(10);
array.push_back(20);
array.push_back(30);
array.push_back(40);
cout << " Inserted into vector. ";
PrintVector(array);
array.pop_back();
array.pop_back();
cout << "Popped two from vector. ";
PrintVector(array);
array.clear();
cout << " Cleared vector. ";
PrintVector(array);
cout << endl;
if(array.empty() == true)
cout << "Vector is empty.";
else
cout << "Vector is NOT empty.";
cout << endl << endl;
return 1;
}


the demo application creates an integer array and populates it with data using the push_back()method . The container is empty until items are pushed onto it. Once on the list, the array [] operators can be used to access the element by reading or writing to it. In the example code four items are pushed onto the list before popping  (removal) of the last two and displaying the contents of the container.
The container is cleared, displayed again, and tested to see if it is empty. Inside
the function used to print a container, the code uses size()to determine how many
valid elements are currently pushed onto the container while capacity()is used to
determine how much space the container can hold without being resized. To access
the elements, we use the array operators [] for convenience.

The Entire Ordered and Unordered Array Classes

template<class T>
class UnorderedArray
{
public:
UnorderedArray(int size, int growBy = 1) :
m_array(NULL), m_maxSize(0),
m_growSize(0), m_numElements(0)
{
if(size)
{
m_maxSize = size;
m_array = new T[m_maxSize];
memset(m_array, 0, sizeof(T) * m_maxSize);
m_growSize = ((growBy > 0) ? growBy : 0);
}
}
virtual ~UnorderedArray()
{
if(m_array != NULL)
{
delete[] m_array;
m_array = NULL;
}
}
virtual void push(T val)
{
assert(m_array != NULL);
if(m_numElements >= m_maxSize)
{
Expand();
}
m_array[m_numElements] = val;
m_numElements++;
}
void pop()
{
if(m_numElements > 0)
m_numElements—;
}
void remove(int index)
{
assert(m_array != NULL);
if(index >= m_maxSize)
{
return;
}
for(int k = index; k < m_maxSize - 1; k++)
m_array[k] = m_array[k + 1];
m_maxSize—;
if(m_numElements >= m_maxSize)
m_numElements = m_maxSize - 1;
}
virtual T& operator[](int index)
{
assert(m_array != NULL && index <= m_numElements);
return m_array[index];
}
virtual int search(T val)
{
assert(m_array != NULL);
for(int i = 0; i < m_numElements; i++)
{
if(m_array[i] == val)
return i;
}
return -1;
}
void clear() { m_numElements = 0; }
int GetSize() { return m_numElements; }
int GetMaxSize() { return m_maxSize; }
int GetGrowSize() { return m_growSize; }
void SetGrowSize(int val)
{
assert(val >= 0);
m_growSize = val;
}
private:
bool Expand()
{
if(m_growSize <= 0)
return false;
T *temp = new T[m_maxSize + m_growSize];
assert(temp != NULL);
memcpy(temp, m_array, sizeof(T) * m_maxSize);
delete[] m_array;
m_array = temp;
m_maxSize += m_growSize;
return true;
}
private:
T *m_array;
int m_maxSize;
int m_growSize;
int m_numElements;
};

Ordered Array Class

template <class T>
class OrderedArray
{
public:
OrderedArray(int size, int growBy = 1) :
m_array(NULL), m_maxSize(0),
m_growSize(0), m_numElements(0)
{
if(size)
{
m_maxSize = size;
m_array = new T[m_maxSize];
memset(m_array, 0, sizeof(T) * m_maxSize);
m_growSize = ((growBy > 0) ? growBy : 0);
}
}
virtual ~OrderedArray()
{
if(m_array != NULL)
{
delete[] m_array;
m_array = NULL;
}
}
void push(T val)
{
assert(m_array != NULL);
if(m_numElements >= m_maxSize)

{
Expand();
}
for(int i = 0; i < m_numElements; i++)
{
if(m_array[i] > val)
break;
}
for(int k = m_numElements; k > i; k—)
{
m_array[k] = m_array[k - 1];
}
m_array[i] = val;
m_numElements++;
}
void pop()
{
if(m_numElements > 0)
m_numElements—;
}
void remove(int index)
{
assert(m_array != NULL);
if(index >= m_maxSize)
{
return;
}
for(int k = index; k < m_maxSize - 1; k++)
m_array[k] = m_array[k + 1];
m_maxSize—;
if(m_numElements >= m_maxSize)
m_numElements = m_maxSize - 1;

}
// Making this const allows for reading but not writing.
virtual const T& operator[](int index)
{
assert(m_array != NULL && index <= m_numElements);
return m_array[index];
}
int search(T searchKey)
{
if(!m_array)
return -1;
int lowerBound = 0;
int upperBound = m_numElements - 1;
int current = 0;
while(1)
{
current = (lowerBound + upperBound) >> 1;
if(m_array[current] == searchKey)
{
return current;
}
else if(lowerBound > upperBound)
{
return -1;
}
else
{
if(m_array[current] < searchKey)
lowerBound = current + 1;
else
upperBound = current - 1;
}
}
return -1;
}
void clear() { m_numElements = 0; }
int GetSize() { return m_numElements; }
int GetMaxSize() { return m_maxSize; }
int GetGrowSize() { return m_growSize; }
void SetGrowSize(int val)
{
assert(val >= 0);
m_growSize = val;
}
private:
bool Expand()
{
if(m_growSize <= 0)
return false;
T *temp = new T[m_maxSize + m_growSize];
assert(temp != NULL);
memcpy(temp, m_array, sizeof(T) * m_maxSize);
delete[] m_array;
m_array = temp;
m_maxSize += m_growSize;
return true;
}
private:
T *m_array;
int m_maxSize;
int m_growSize;
int m_numElements;
};

BINARY SEARCHES

A binary search can be performed on an ordered array. It works by taking a value
that is being searched for and testing it by the element in the middle of the array. If
the value being searched for is lower than the item in the middle of the ordered
array, it can be determined that if the value exists, it is in the first half of the array.
If the value is larger than the element in the middle, the value might exist in the
upper half. Once the direction is known, half of that new section is tested to further
narrow down where the value can be. This is repeated until the value is found or
until there are no more elements left. The binary search gets its name from the fact
that the remaining elements are always split in half (binary equals 2). Because a binary search requires the elements to be in order, this algorithm cannot work for an unordered array since the
unordered array can be unpredictable in terms of item positions.
The binary search can eliminate large sections of an array in an effort to narrow
down the list to find the value, assuming it exits. When compared to the linear
search, this can result in a huge difference in performance as Ngrows larger. For example, an array being searched with a linear algorithm that is made up of 1 million
elements will take on average 500,000 steps for items that exist, which can mean
that some checks can go up to the whole million depending on the item. Using a
binary search on an ordered array with that same number of elements will take
20 comparisons. To go from an average of 500,000 comparisons to just 20 is a huge
difference. To go from 1 million comparisons to 20 with items that are not found


while(1)
{
current = (lowerBound + upperBound) >> 1;
if(m_array[current] == searchKey)
{
return current;
}
else if(lowerBound > upperBound)
{
return -1;
}
else
{
if(m_array[current] < searchKey)
lowerBound = current + 1;
else
upperBound = current - 1;
}
}
return -1;
}
};


The binary search  starts off by defining the bounds that make up
the search range, which is initially set to the entire array. Once the range is set, the
middle of the range is determined and the element at the position is tested. If the
item is found, the index is returned; if the lower bound’s value becomes higher than
the upper bound’s value (which will happen when the search has stepped through
the entire array), then the value is not found. If neither of these two cases are true,
the lower bound, which is the minimum search range position, is adjusted if
the item is greater than the item in the middle, or else the upper bound is adjusted.
Adjusting the range values will quickly shrink the search range until the value is
found or until there are no more elements to check this

operation is pretty fast as N grows larger.


BASICSEARCHES

When we are looking for a value in an unordered array, our main option is the
linear search. The linear search is a brute-force-style search. The algorithm works
by stepping through each element of the array, starting with the first element, and
checking to see if the value of that element matches the value of what is being
searched for. If it is found, then the algorithm can report that the item exists in
some meaningful fashion, and it can also report where in the array the item is
positioned.
During a linear search the algorithm can find the first occurrence or all occurrences of a value. If duplicates are allowed in the array, then more than one value
can exist. In this chapter we’ll discuss finding the first occurrence. If there are times
when you know you need to know how many occurrences there are, or even how
many and where they are, then the searching function of the unordered array class
can be expanded to accommodate those needs. Searching beyond the first occurrence can be a waste of CPU time if there is no need to look for duplicates.

template<class T>
class UnorderedArray
{
public:
virtual int search(T val)
{
assert(m_array != NULL);
for(int i = 0; i < m_numElements; i++)
{
if(m_array[i] == val)
return i;
}
return -1;
}
};
A linear search can become slow for arrays with large numbers of items. On
average, the algorithm requires half the total number of items to find a value. If
there were 100 items in a list, then the average would be 50. Because the linear
search’s performance is based on the number of items in the array, it has a big-O of
O(N). The linear search is the most basic, yet slowest, search because it must check
potentially every item (half on average) before finding a value, assuming the value
even exists in the array. If the value does not exist, the search would have checked
every element in the array and come up with nothing.

The Ordered Array Class that Differs from the Unordered Array

template <class T>
class OrderedArray
{
public:
int push(T val)
{
assert(m_array != NULL);
if(m_numElements >= m_maxSize)
{
Expand();
}
for(int i = 0; i < m_numElements; i++)
{
if(m_array[i] > val)
break;
}
for(int k = m_numElements; k > i; k—)
{
m_array[k] = m_array[k - 1];
}
m_array[i] = val;
m_numElements++;
return i;
}
};
Another option for inserting an item into an ordered array is to use a modified binary search to find the index closest to where the item would need to be inserted
and start the stepping from that point.

Removing Items from the Unordered Array

template<class T>
class UnorderedArray
{
public:
void pop()
{
if(m_numElements > 0)
m_numElements—;
}
void remove(int index)a
{
assert(m_array != NULL);
if(index >= m_maxSize)
{
return;
}
for(int k = index; k < m_maxSize - 1; k++)
m_array[k] = m_array[k + 1];
m_maxSize—;
if(m_numElements >= m_maxSize)
m_numElements = m_maxSize - 1;
}
};

Monday 23 December 2013

Using JDBC with Spring

There are many persistence technologies out there. Hibernate, iBATIS, and JPAare
just a few. Despite this, a good number of applications are writing Java objects to a
database the old-fashioned way: they earn it. No, wait—that’s how people make
money. The tried-and-true method for persisting data is with good old JDBC.
And why not? JDBCdoesn’t require mastering another framework’s query language. It’s built on top of SQL, which is the data access language. Plus, you can more
finely tune the performance of your data access when you use JDBCthan with practically any other technology. And JDBCallows you to take advantage of your database’s
proprietary features, where other frameworks may discourage or flat-out prohibit this.
What’s more, JDBClets you work with data at a much lower level than the persistence frameworks, allowing you to access and manipulate individual columns in a
database. This fine-grained approach to data access comes in handy in applications,
such as reporting applications, where it doesn’t make sense to organize the data into
objects, just to then unwind it back into raw data.
But all is not sunny in the world of JDBC. With its power, flexibility, and other niceties also come some not-so-niceties.
Tackling runaway JDBC code
Though JDBCgives you an APIthat works closely with yourdatabase, you’re responsible for handling everything related to accessing the database. This includes managing
database resources and handling exceptions.
If you’ve ever written JDBCthat inserts data into the database, the following
shouldn’t be too alien to you.

private static final String SQL_INSERT_SPITTER =
"insert into spitter (username, password, fullname) values (?, ?, ?)";
private DataSource dataSource;
public void addSpitter(Spitter spitter) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement(SQL_INSERT_SPITTER);
stmt.setString(1, spitter.getUsername());
stmt.setString(2, spitter.getPassword());
stmt.setString(3, spitter.getFullName());
stmt.execute();
} catch (SQLException e) {
// do something...not sure what, though
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// I'm even less sure about what to do here
}
}
}

private static final String SQL_UPDATE_SPITTER =
"update spitter set username = ?, password = ?, fullname = ?"
+ "where id = ?";
public void saveSpitter(Spitter spitter) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = dataSource.getConnection();

stmt = conn.prepareStatement(SQL_UPDATE_SPITTER);
stmt.setString(1, spitter.getUsername());
stmt.setString(2, spitter.getPassword());
stmt.setString(3, spitter.getFullName());
stmt.setLong(4, spitter.getId());
stmt.execute();
} catch (SQLException e) {
// Still not sure what I'm supposed to do here
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// or here
}
}

}

private static final String SQL_SELECT_SPITTER =
"select id, username, fullname from spitter where id = ?";
public Spitter getSpitterById(long id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
stmt = conn.prepareStatement(SQL_SELECT_SPITTER);
stmt.setLong(1, id);
rs = stmt.executeQuery();
Spitter spitter = null;
if (rs.next()) {
spitter = new Spitter();
spitter.setId(rs.getLong("id"));
spitter.setUsername(rs.getString("username"));

spitter.setPassword(rs.getString("password"));
spitter.setFullName(rs.getString("fullname"));
}
return spitter;
} catch (SQLException e) {
} finally {
if(rs != null) {
try {
rs.close();
} catch(SQLException e) {}
}
if(stmt != null) {
try {
stmt.close();
} catch(SQLException e) {}
}
if(conn != null) {
try {
conn.close();
} catch(SQLException e) {}
}
}
return null;

}

Working with JDBC templates

Spring’s JDBC framework will clean up your JDBCcode by shouldering the burden of
resource management and exception handling. This leaves you free to write only the

code necessary to move data to and from the database.
All that a SimpleJdbcTemplateneeds to do its work is a DataSource. This makes it easy
enough to configure a SimpleJdbcTemplatebean in Spring with the following XML:
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
The actual DataSourcebeing referred to by the dataSourceproperty can be any
implementation of javax.sql.DataSource, including those we created in section 5.2.
Now we can wire the jdbcTemplatebean into our DAOand use it to access the database. For example, suppose that the Spitter DAOis written to use SimpleJdbcTemplate:
public class JdbcSpitterDAO implements
SpitterDAO {
...
private SimpleJdbcTemplate jdbcTemplate;
public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
You’d then wire the jdbcTemplateproperty of JdbcSpitterDAOas follows:
<bean id="spitterDao"
class="com.habuma.spitter.persistence.SimpleJdbcTemplateSpitterDao">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>

With a SimpleJdbcTemplateat our DAO’s disposal, we can greatly simplify the
addSpitter()method from listing The new SimpleJdbcTemplate-based

addSpitter()method is shown next.

public void addSpitter(Spitter spitter) {
jdbcTemplate.update(SQL_INSERT_SPITTER,
spitter.getUsername(),
spitter.getPassword(),
spitter.getFullName(),
spitter.getEmail(),
spitter.isUpdateByEmail());
spitter.setId(queryForIdentity());
}

Querying for a Spitterusing SimpleJdbcTemplate

public Spitter getSpitterById(long id) {
return jdbcTemplate.queryForObject(
SQL_SELECT_SPITTER_BY_ID,
new ParameterizedRowMapper<Spitter>() {
public Spitter mapRow(ResultSet rs, int rowNum)
throws SQLException {
Spitter spitter = new Spitter();
spitter.setId(rs.getLong(1));
spitter.setUsername(rs.getString(2));
spitter.setPassword(rs.getString(3));
spitter.setFullName(rs.getString(4));
return spitter;
}
},
id
);
}

Using named parameters with Spring JDBC templates

public void addSpitter(Spitter spitter) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("username", spitter.getUsername());
params.put("password", spitter.getPassword());
params.put("fullname", spitter.getFullName());
jdbcTemplate.update(SQL_INSERT_SPITTER, params);
spitter.setId(queryForIdentity());

}

USING SPRING’S DAO SUPPORT CLASSES FOR JDBC

public class JdbcSpitterDao extends SimpleJdbcDaoSupport
implements SpitterDao {
...

}


public void addSpitter(Spitter spitter) {
getSimpleJdbcTemplate().update(SQL_INSERT_SPITTER,
spitter.getUsername(),
spitter.getPassword(),
spitter.getFullName(),
spitter.getEmail(),
spitter.isUpdateByEmail());
spitter.setId(queryForIdentity());
}

When configuring your DAOclass in Spring, you could directly wire a SimpleJdbcTemplatebean into its jdbcTemplateproperty as follows:
<bean id="spitterDao"
 class="com.habuma.spitter.persistence.JdbcSpitterDao"> <property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>

This will work,

Wednesday 18 December 2013

Cascading in JPA

To begin, let’s consider the changes required to make the persist()operation cascade from Employee
to Address. In the definition of the Employeeclass, there is a @ManyToOne annotation defined for the
address relationship. To enable the cascade, we must add the PERSISToperation to the list of cascading
operations for this relationship of the Employee entity that
demonstrates this change.
.Enabling Cascade Persist
@Entity
public class Employee {
// ...
@ManyToOne(cascade=CascadeType.PERSIST)
Address address;
// ...
}
To leverage this change, we need only ensure that the Add ressentity has been set on the Employee
instance before invoking persist()on it. As the entity manager encounters the Employee instance and
adds it to the persistence context, it will navigate across the address relationship looking for a new
Address entity to manage as well. In comparison with the approach in Listing
Cascade settings are unidirectional. This means that they must be explicitly set on both sides of a
relationship if the same behavior is intended for both situations. For example, in Listing, we only
added the cascade setting to the address relationship in the Employee entity. If Listing were
changed to persist only the Address entity, not the Employee entity, the Employee entity would not
become managed because the entity manager has not been instructed to navigate out from any
relationships defined on the Address entity.

Saturday 7 December 2013

The Database Life Cycle



Before getting into the development of any system, you need to have strong a life-cycle model to follow. The model must have all the phases defined in the proper sequence, which will help the development team build the system with fewer problems and full functionality as expected.
The database life cycle consists of the following stages, from the basic steps involved in designing a global schema of the database to database implementation and maintenance:
•  Requirements analysis: Requirements need to be determined before you can begin design and implementation. The requirements can be gathered by interviewing
both the producer and the user of the data; this process helps in creating a formal requirement specification.
•  Logical design: After requirements gathering, data and relationships need to be
defined using a conceptual data modeling technique such as an entityrelationship (ER) diagram. This diagram shows how one object will connect to the other one and by what relationship (one-one or one-many). Relationships are.
•  Physical design: Once the logical design is in place,the next step is to produce the
physical structure for the database. The physical design phase involves creating
tables and selecting indexes.but an index is basically like an index of a book, which allows you to jump to a
particular page based on the topic of your choice and helps you avoid shuffling all
the pages of the book to reach the page of interest. Database indexes do
something similar; they manage and maintain the order of rows when inserted
into the table, which helps SQL queries pull data fast based on a provided value for
the index column.
Database implementation: Once the design is completed, the database can be
created through the implementation of formal schema using the data definition
language (DDL) of the RDBMS. The DDL consists of the statements that play key
roles in creating, modifying, and deleting the database or database objects. CREATE,
ALTER, and DROP are prime examples of a DDL.
Data modification: A data modification language (DML) can be used to query and
update the database as well as set up indexes and establish constraints such as referential integrity. A DML consists of the statements that play key roles in inserting,
updating and deleting the data from database tables. INSERT, UPDATE, and DELETE
are prime examples of a DDL.
•  Database monitoring: As the database begins operation, monitoring indicates
whether performance requirements are being met; if they are not, modifications
should be made to improve database performance. Thus, the database life cycle
continues with monitoring, redesign, and modification. 

Why Use a Database?

The following are some of the reasons why you would use databases:
•  Compactness: Databases help you maintain large amounts of data and thus completely replace voluminous paper files.
•  Speed: Searches for a particular piece of data or information in a database are
much faster than sorting through piles of paper.

 Less drudgery: It is a dull work to maintain files by hand; using a database completely eliminates such maintenance.
•  Currency: Database systems can easily be updated and so provide accurate information all the time and on demand.

Benefits of Using a RelationalDatabase Management System 

RDBMSs offer various benefits by controlling the following:
•  Redundancy: RDBMSs prevent you from having duplicate copies of the same data,
which takes up disk space unnecessarily.
•  Inconsistency: Each redundant set of data may no longer agree with other sets of
the same data. When an RDBMS removes redundancy, inconsistency cannot
occur.
•  Data integrity: Data values stored in the database must satisfy certain types of
consistency constraints.
•  Data atomicity: In event of a failure, data is restored to the consistent state it
existed in prior to the failure. For example, fund transfer activity must be atomic.
•  Access anomalies: RDBMSs prevent more than one user from updating the same
data simultaneously; such concurrent updates may result in inconsistent data.
 Data security: Not every user of the database system should be able to access all
the data. Security refers to the protection of data against any unauthorized access.
•  Transaction processing: A transaction is a sequence of database operations that
represents a logical unit of work. In RDBMSs, a transaction either commits all the
changes or rolls back all the actions performed until the point at which the failure
occurred.
•  Recovery: Recovery features ensure that data is reorganized into a consistent state
after a transaction fails.
•  Storage management: RDBMSs provide a mechanism for data storage
management. The internal schema defines how data should be stored.

Comparing Desktop and Server RDBMS Systems 

In the industry today, you’ll mainly work with two types of databases: desktop databases and server
databases
Desktop Databases 
Desktop databases are designed to serve a limited number of users and run on desktop PCs, and they
offer a less-expansive solution wherever a database is required. Chances are you have worked with a
desktop database program; Microsoft SQL Server Express, Microsoft Access, Microsoft FoxPro,
FileMaker Pro, Paradox, and Lotus are all desktop database solutions.
Desktop databases differ from server databases in the following ways: 
•  Less expensive: Most desktop solutions are available for just a few hundred dollars.
In fact, if you own a licensed version of Microsoft Office Professional, you’re
already a licensed owner of Microsoft Access, which is one of the most commonly
and widely used desktop database programs around.
•  User friendly: Desktop databases are quite user friendly and easy to work with,
because they do not require complex SQL queries to perform database operations
(although some desktop databases also support SQL syntax if you want to write
code). Desktop databases generally offer an easy-to-use graphical user interface.
Server Databases 
Server databases are specifically designed to serve multiple users at a time and offer features that allow
you to manage large amounts of data very efficiently by serving multiple user requests simultaneously.
Well-known examples of server databases include Microsoft SQL Server, Oracle, Sybase, and DB2.
The following are some other characteristics that differentiate server databases from their desktop
counterparts:
•  Flexibility: Server databases are designed to be very flexible and support multiple
platforms, respond to requests coming from multiple database users, and perform
any database management task with optimum speed.
•  Availability: Server databases are intended for enterprises, so they need to be
available 24/7. To be available all the time, server databases come with some highavailability features, such as mirroring and log shipping.
•  Performance: Server databases usually have huge hardware support, so servers
running these databases have large amountsof RAM and multiple CPUs. This is
why server databases support rich infrastructure and give optimum performance.
•  Scalability: This property allows a server database to expand its ability to process
and store records even if it has grown tremendously.

Using Layout Controls

Although you can use fixed positioning to place controls on a WPF window, it’s
positioning usually works well for a fixed resolution size but it doesn’t scale we
To overcome the limitations of fixed positioning, WPF offers several layout con
position other controls within it using a relative positioning format. One of the
other controls is the Grid. As seen previous post, a Grid control contains columns
its child controls. The height and width of the columns and rows can be set to a
takes up as much space as needed by the contained control. The *setting take
The Grid control is often used to lay out data entry forms. The following code l
collect user information. The resulting form (in the Visual Studio designer) is s
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="28" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Name:"/>
<Label Grid.Row="1" Grid.Column="0" Content="Old Password:"/>
<Label Grid.Row="2" Grid.Column="0" Content="New Password:"/>
<Label Grid.Row="3" Grid.Column="0" Content="Confirm Password:
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" />
<TextBox Grid.Column="1" Grid.Row="2" Margin="3" />
<TextBox Grid.Column="1" Grid.Row="3" Margin="3" />
<Button Grid.Column="1" Grid.Row="4" HorizontalAlignment="Righ
MinWidth="80" Margin="0,0,0,8" Content="Submit" />
</Grid>
Photo

XAML

WPF user interfaces are built using a declarative markup language called XAML. XAML declares the controls that will
make up the interface. An opening angle bracket (<) followed by the name of the control type and a closing bracket
define the control. For example, the following markup defines a button control inside a Grid.
<Grid>

<Button/>

</Grid>
Notice the Grid needs a formal closing tag because it contains the Button control. Since the Button control does not contain any other elements, you can use a forward slash (/) in front of the end bracket to close it
The next step is to define the properties of the controls. For example, you may want to set the background colour of the button to red and write some text on it. The properties of the control are set by using attribute syntax, which consists of the property name followed by an equal sign and the attribute value in quotation marks. The following mark-up shows the Button control with some attributes added:

<Grid>
<Button Content="Click Me" Background="Red"/>
</Grid>
For some properties of an object element a syntax known as property element syntax is used. The syntax for the property element start tag is <typeName.propertyName>. For example, you can create rows and columns in the layout grid to control placement of controls in the grid, as shown:

<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="25" />
<RowDefinition Height="25" />
</Grid.RowDefinitions>
Controls are positioned in the grid by including a Grid.Rowand Grid.Columnattribute, as shown:
<Label Grid.Column="0" Grid.Row="0" Content="Name:" />
<Label Grid.Column="0" Grid.Row="1" Content="Password:" />
<TextBox Name="txtName" Grid.Column="1" Grid.Row="0"/>
<TextBox Name="txtPassword" Grid.Column="1" Grid.Row="1"/>
<Button Grid.Column="1" Grid.Row="3"
Content="Click Me" HorizontalAlignment="Right"
MinWidth="80" Background="Red"/>

Photo