Following is an example how to read the file and display using System.out.println()
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileReader {
public static void main(String[] args) {
String file = "C:\\Users\\test.csv";
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
while (reader.readLine() != null) {
System.out.println(reader.readLine());
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Sunday, July 15, 2012
Upload File using JSF 2.0 and Richfaces
Given below is a simple application how we can upload file using JSF 2.0. The example contain three files
1. The main FileUploadController which has much of the funtionalities for uploading saving files
2. The UploadedText is the bean containing information about the file and
3. The upload.xhtml JSF page.
First Create FileUploadController
Next Create the UploadText file:
Finally Create the JSF file:
1. The main FileUploadController which has much of the funtionalities for uploading saving files
2. The UploadedText is the bean containing information about the file and
3. The upload.xhtml JSF page.
First Create FileUploadController
1: import java.io.File;
2: import java.io.FileOutputStream;
3: import java.io.IOException;
4: import java.io.OutputStream;
5: import java.io.Serializable;
6: import java.util.ArrayList;
7: import org.apache.log4j.Logger;
8: import org.richfaces.event.FileUploadEvent;
9: import org.richfaces.model.UploadedFile;
10: import org.springframework.context.annotation.Scope;
11: import org.springframework.stereotype.Component;
12: import com.jsf.app.client.vo.UploadedText;
13: // spring managed bean
14: @Component("fileUploadController")
15: @Scope("session")
16: public class FileUploadController implements Serializable {
17: private static final long serialVersionUID = -4664762090820133359L;
18: private static final Logger logger = Logger.getLogger(FileUploadBean.class
19: .getName());
20: private static final String fPath = "C:\\Users\\";
21: private ArrayList<UploadedText> files = new ArrayList<UploadedText>();
22: public void paint(OutputStream stream, Object object) throws IOException {
23: stream.write(getFiles().get((Integer) object).getData());
24: stream.close();
25: }
26: public void listener(FileUploadEvent event) throws Exception {
27: UploadedFile item = event.getUploadedFile();
28: UploadedText file = new UploadedText();
29: file.setLength(item.getData().length);
30: file.setName(item.getName());
31: file.setData(item.getData());
32: files.add(file);
33: }
34: public String clearUploadData() {
35: files.clear();
36: return null;
37: }
38: public int getSize() {
39: if (getFiles().size() > 0) {
40: return getFiles().size();
41: } else {
42: return 0;
43: }
44: }
45: public long getTimeStamp() {
46: return System.currentTimeMillis();
47: }
48: public ArrayList<UploadedText> getFiles() {
49: return files;
50: }
51: public void setFiles(ArrayList<UploadedText> files) {
52: this.files = files;
53: }
54: public void writeFile() {
55: FileOutputStream fop = null;
56: File file;
57: UploadedText contain = files.size() > 0 ? files.get(0) : null;
58: if (contain == null) {
59: return;
60: }
61: try {
62: file = new File(fPath + contain.getName());
63: fop = new FileOutputStream(file);
64: if (!file.exists()) {
65: file.createNewFile();
66: }
67: fop.write(contain.getData());
68: fop.flush();
69: fop.close();
70: if (logger.isDebugEnabled()) {
71: logger.debug("File Creation Completed Successfuly.");
72: }
73: } catch (IOException e) {
74: e.printStackTrace();
75: } finally {
76: try {
77: if (fop != null) {
78: fop.close();
79: }
80: } catch (IOException e) {
81: e.printStackTrace();
82: }
83: }
84: }
85: }
Next Create the UploadText file:
1: import java.io.Serializable;
2: public class UploadedText implements Serializable {
3: private static final long serialVersionUID = -3957467715082208719L;
4: private String name;
5: private String mime;
6: private long length;
7: private byte[] data;
8: public String getName() {
9: return name;
10: }
11: public void setName(String name) {
12: int extDot = name.lastIndexOf('.');
13: if (extDot > 0) {
14: String extension = name.substring(extDot + 1);
15: if ("txt".equals(extension)) {
16: mime = "text/plain";
17: } else if ("csv".equals(extension)) {
18: mime = "text/csv";
19: } else {
20: mime = "text/unknown";
21: }
22: }
23: this.name = name;
24: }
25: public String getMime() {
26: return mime;
27: }
28: public void setMime(String mime) {
29: this.mime = mime;
30: }
31: public long getLength() {
32: return length;
33: }
34: public void setLength(long length) {
35: this.length = length;
36: }
37: public byte[] getData() {
38: return data;
39: }
40: public void setData(byte[] data) {
41: this.data = data;
42: }
43: }
Finally Create the JSF file:
1: <?xml version='1.0' encoding='UTF-8' ?>
2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3: <html xmlns="http://www.w3.org/1999/xhtml"
4: xmlns:f="http://java.sun.com/jsf/core"
5: xmlns:h="http://java.sun.com/jsf/html"
6: xmlns:ui="http://java.sun.com/jsf/facelets"
7: xmlns:a4j="http://richfaces.org/a4j"
8: xmlns:rich="http://richfaces.org/rich">
9: <h:body>
10: <ui:composition template="template/common/commonLayout.xhtml">
11: <ui:define name="content">
12: <h:form>
13: <h:panelGrid columns="2" columnClasses="top,top">
14: <rich:fileUpload fileUploadListener="#{fileUploadController.listener}"
15: id="upload" acceptedTypes="txt,csv"
16: ontyperejected="alert('Only Text and CSV files are accepted');"
17: maxFilesQuantity="1">
18: <a4j:ajax event="uploadcomplete" execute="@none" render="info" />
19: </rich:fileUpload>
20: </h:panelGrid>
21: <h:panelGroup id="info">
22: <rich:dataGrid columns="1" value="#{fileUploadController.files}"
23: var="file" rowKeyVar="row">
24: <rich:panel bodyClass="rich-laguna-panel-no-header">
25: <h:panelGrid columns="2">
26: <a4j:mediaOutput element="img" mimeType="image/jpeg"
27: createContent="#{fileUploadController.paint}" value="#{row}"
28: style="width:100px; height:100px;" cacheable="false">
29: <f:param value="#{fileUploadController.timeStamp}" name="time" />
30: </a4j:mediaOutput>
31: <h:panelGrid columns="2">
32: <h:outputText value="File Name:" />
33: <h:outputText value="#{file.name}" />
34: <h:outputText value="File Length(bytes):" />
35: <h:outputText value="#{file.length}" />
36: </h:panelGrid>
37: </h:panelGrid>
38: </rich:panel>
39: </rich:dataGrid>
40: <a4j:commandButton action="#{fileUploadController.clearUploadData}"
41: render="info, upload" value="Clear Uploaded Data"
42: rendered="#{fileUploadController.size>0}" />
43: <a4j:commandButton action="#{fileUploadController.writeFile}"
44: value="Write file to Disk" rendered="#{fileUploadController.size>0}" />
45: </h:panelGroup>
46: </h:form>
47: </ui:define>
48: </ui:composition>
49: </h:body>
50: </html>
Thursday, June 28, 2012
How to Download File using JSF
Following is the simple example how to download file from Server using JSF application
1. Create new JSF bean, either ManageBean or Component Bean using Spring framework
2. Now Access the file using the JSF link as shown below:
3. Create web.xml something like:
Now after deploying this in the servlets container, you will see the dialog box for Save the File/Open.
1. Create new JSF bean, either ManageBean or Component Bean using Spring framework
1: package com.jsf.app.managedbean;
2: import java.io.BufferedInputStream;
3: import java.io.BufferedOutputStream;
4: import java.io.File;
5: import java.io.FileInputStream;
6: import java.io.IOException;
7: import javax.faces.context.FacesContext;
8: import javax.servlet.http.HttpServletResponse;
9: import javax.faces.bean.ManagedBean;
10: @ManagedBean(name="fileDownloadBean")
11: public class FileDownloadBean {
12: private static final int DEFAULT_BUFFER_SIZE = 10240;
13: private String filePath = "c:\\download\\test.txt";
14: public void downLoad() throws IOException {
15: FacesContext context = FacesContext.getCurrentInstance();
16: HttpServletResponse response = (HttpServletResponse) context
17: .getExternalContext().getResponse();
18: File file = new File(filePath);
19: if (!file.exists()) {
20: response.sendError(HttpServletResponse.SC_NOT_FOUND);
21: return;
22: }
23: response.reset();
24: response.setBufferSize(DEFAULT_BUFFER_SIZE);
25: response.setContentType("application/octet-stream");
26: response.setHeader("Content-Length", String.valueOf(file.length()));
27: response.setHeader("Content-Disposition", "attachment;filename=\""
28: + file.getName() + "\"");
29: BufferedInputStream input = null;
30: BufferedOutputStream output = null;
31: try {
32: input = new BufferedInputStream(new FileInputStream(file),
33: DEFAULT_BUFFER_SIZE);
34: output = new BufferedOutputStream(response.getOutputStream(),
35: DEFAULT_BUFFER_SIZE);
36: byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
37: int length;
38: while ((length = input.read(buffer)) > 0) {
39: output.write(buffer, 0, length);
40: }
41: } finally {
42: input.close();
43: output.close();
44: }
45: context.responseComplete();
46: }
47: }
2. Now Access the file using the JSF link as shown below:
1: <h:form>
2: <h:commandLink id="getDownload" value="Download Files"
3: action="#{fileDownloadBean.downLoad}">
4: </h:commandLink>
5: </h:form>
3. Create web.xml something like:
1: <?xml version="1.0" encoding="UTF-8"?>
2: <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3: xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
4: xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
5: http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
6: id="WebApp_ID" version="2.5">
7: <listener>
8: <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
9: </listener>
10: <context-param>
11: <param-name>javax.faces.PROJECT_STAGE</param-name>
12: <param-value>Development</param-value>
13: </context-param>
14: <context-param>
15: <param-name>javax.faces.CONFIG-FILES</param-name>
16: <param-value>WEB-INF/faces-config.xml</param-value>
17: </context-param>
18: <context-param>
19: <param-name>com.sun.faces.expressionFactory</param-name>
20: <param-value>com.sun.el.ExpressionFactoryImpl</param-value>
21: </context-param>
22: <servlet>
23: <servlet-name>Faces Servlet</servlet-name>
24: <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
25: <load-on-startup>1</load-on-startup>
26: </servlet>
27: <servlet-mapping>
28: <servlet-name>Faces Servlet</servlet-name>
29: <url-pattern>/faces/*</url-pattern>
30: </servlet-mapping>
31: <servlet-mapping>
32: <servlet-name>Faces Servlet</servlet-name>
33: <url-pattern>*.jsf</url-pattern>
34: </servlet-mapping>
35: <servlet-mapping>
36: <servlet-name>Faces Servlet</servlet-name>
37: <url-pattern>*.faces</url-pattern>
38: </servlet-mapping>
39: <servlet-mapping>
40: <servlet-name>Faces Servlet</servlet-name>
41: <url-pattern>*.xhtml</url-pattern>
42: </servlet-mapping>
43: </web-app>
Now after deploying this in the servlets container, you will see the dialog box for Save the File/Open.
Sunday, June 17, 2012
How to create generic Repository Dao in JPA.
Repository Dao is an interface to interact with the low level database operation, specially CRUD operations. The Repository Dao interface is usually designed to hide the implementation details and provide the uniform API to the client of the Dao usually Service classes.
In the below example, I will create the basic domain, Dao Interface, Implementation and Test class for JPA implementation.
1. First Create the database schema as shown below:
2. Create the domain class for the data model shown above:
PersistableId Class
Persistable User Class map to LOGIN_USER table.
3. Now create a generic persistence dao interface:
4. Now create an abstract implementation of the generic persistence dao:
5. We can now create our customized Dao Interface and Implementation for our Domain Objects. In this case for our User domain object as shown below:
and Implementation:
6. Finally create the test case to test the Dao and Implementation:
In the below example, I will create the basic domain, Dao Interface, Implementation and Test class for JPA implementation.
1. First Create the database schema as shown below:
create table login_user(uuid varchar2(40), user_name varchar2(40), password varchar2(100), first_name varchar2(100), last_name varchar2(100));
2. Create the domain class for the data model shown above:
PersistableId Class
1: package com.jsf.app.persistence.model;
2: import java.io.Serializable;
3: import javax.persistence.Column;
4: import javax.persistence.Id;
5: import javax.persistence.MappedSuperclass;
6: import javax.persistence.PrePersist;
7: import com.jsf.app.utils.UUIDGenerator;
8: @MappedSuperclass
9: public class AbstractIdPersistable implements Serializable {
10: private static final long serialVersionUID = -2722115269874427565L;
11: @Id
12: @Column(name = "UUID")
13: private String id;
14: public String getId() {
15: return id;
16: }
17: public void setId(String id) {
18: this.id = id;
19: }
20: public boolean isNew() {
21: return null == getId();
22: }
23: @PrePersist
24: public void assignUUID() {
25: this.setId(UUIDGenerator.getUUID());
26: }
27: }
Persistable User Class map to LOGIN_USER table.
1: package com.jsf.app.persistence.model;
2: import javax.persistence.Column;
3: import javax.persistence.Entity;
4: import javax.persistence.NamedQueries;
5: import javax.persistence.NamedQuery;
6: import javax.persistence.Table;
7: @Entity
8: @Table(name = "LOGIN_USER")
9: @NamedQueries({
10: @NamedQuery(name = "user.findAll", query = "from User"),
11: @NamedQuery(name = "user.findByUserName", query = "from User u where u.userName = ?") })
12: public class User extends AbstractIdPersistable {
13: private static final long serialVersionUID = -6103795542566301215L;
14: @Column(name = "USER_NAME", nullable = false)
15: private String userName;
16: @Column(name = "PASSWORD", nullable = false)
17: private String password;
18: @Column(name = "FIRST_NAME", nullable = false)
19: private String firstName;
20: @Column(name = "LAST_NAME", nullable = false)
21: private String lastName;
22: public String getUserName() {
23: return userName;
24: }
25: public void setUserName(String userName) {
26: this.userName = userName;
27: }
28: public String getPassword() {
29: return password;
30: }
31: public void setPassword(String password) {
32: this.password = password;
33: }
34: public String getFirstName() {
35: return firstName;
36: }
37: public void setFirstName(String firstName) {
38: this.firstName = firstName;
39: }
40: public String getLastName() {
41: return lastName;
42: }
43: public void setLastName(String lastName) {
44: this.lastName = lastName;
45: }
46: @Override
47: public String toString() {
48: return "[" + this.getId() + ", " + this.getFirstName() + ", "
49: + this.getLastName() + "]";
50: }
51: }
3. Now create a generic persistence dao interface:
1: package com.jsf.app.persistence.dao;
2: import java.util.Collection;
3: public interface AbstractPersistenceDao<Entity> {
4: public Entity findById(String id);
5: public void save(Entity e);
6: public void remove(Entity e);
7: public Collection<Entity> findByNamedQuery(String nameQuery);
8: public Collection<Entity> findByNamedQueryAndParams(String nameQuery,
9: Object... params);
10: }
4. Now create an abstract implementation of the generic persistence dao:
1: package com.jsf.app.persistence.dao.impl;
2: import java.lang.reflect.ParameterizedType;
3: import java.util.Collection;
4: import javax.persistence.EntityManager;
5: import javax.persistence.PersistenceContext;
6: import javax.persistence.Query;
7: import com.jsf.app.persistence.dao.AbstractPersistenceDao;
8: public abstract class AbstractPersistenceDaoImpl<Entity> implements
9: AbstractPersistenceDao<Entity> {
10: @PersistenceContext
11: private EntityManager entityManager;
12: public AbstractPersistenceDaoImpl() {
13: }
14: @SuppressWarnings("unchecked")
15: public Class<Entity> returnEntityClass() {
16: ParameterizedType genericSuperclass = (ParameterizedType) getClass()
17: .getGenericSuperclass();
18: return (Class<Entity>) genericSuperclass.getActualTypeArguments()[0];
19: }
20: @Override
21: public Entity findById(String id) {
22: return entityManager.find(returnEntityClass(), id);
23: }
24: @Override
25: public void save(Entity e) {
26: this.entityManager.persist(e);
27: }
28: @Override
29: public void remove(Entity e) {
30: this.entityManager.remove(e);
31: }
32: @Override
33: @SuppressWarnings("unchecked")
34: public Collection<Entity> findByNamedQuery(String query) {
35: Query q = this.entityManager.createNamedQuery(query);
36: return (Collection<Entity>) q.getResultList();
37: }
38: @Override
39: @SuppressWarnings("unchecked")
40: public Collection<Entity> findByNamedQueryAndParams(String nameQuery,
41: Object... params) {
42: Query q = entityManager.createNamedQuery(nameQuery);
43: int i = 1;
44: for (Object o : params) {
45: q.setParameter(i, o);
46: }
47: return (Collection<Entity>) q.getResultList();
48: }
49: }
5. We can now create our customized Dao Interface and Implementation for our Domain Objects. In this case for our User domain object as shown below:
1: package com.jsf.app.persistence.dao;
2: import java.util.Collection;
3: import com.jsf.app.persistence.model.User;
4: public interface UserDao extends AbstractPersistenceDao<User> {
5: public Collection<User> getAllUser();
6: public void persistChange(User user);
7: }
and Implementation:
1: package com.jsf.app.persistence.dao.impl;
2: import java.util.Collection;
3: import org.springframework.stereotype.Repository;
4: import org.springframework.transaction.annotation.Transactional;
5: import com.jsf.app.persistence.dao.UserDao;
6: import com.jsf.app.persistence.model.User;
7: @Repository("userDao")
8: public class UserDaoImpl extends AbstractPersistenceDaoImpl<User> implements
9: UserDao {
10: public UserDaoImpl() {
11: super();
12: }
13: @Override
14: @SuppressWarnings("unchecked")
15: public Collection<User> getAllUser() {
16: return findByNamedQuery("user.findAll");
17: }
18: @Override
19: @Transactional
20: public void persistChange(User user) {
21: save(user);
22: }
23: }
6. Finally create the test case to test the Dao and Implementation:
1: package com.jsf.app.persistence.dao.impl;
2: import java.util.Collection;
3: import java.util.List;
4: import org.junit.After;
5: import org.junit.Assert;
6: import org.junit.Before;
7: import org.junit.Ignore;
8: import org.junit.Test;
9: import org.junit.runner.RunWith;
10: import org.springframework.beans.factory.annotation.Autowired;
11: import org.springframework.test.context.ContextConfiguration;
12: import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13: import org.springframework.test.context.transaction.TransactionConfiguration;
14: import org.springframework.transaction.annotation.Transactional;
15: import com.jsf.app.persistence.dao.UserDao;
16: import com.jsf.app.persistence.model.User;
17: @RunWith(SpringJUnit4ClassRunner.class)
18: @ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
19: @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
20: public class UserDaoTest {
21: @Autowired
22: private UserDao userDao;
23: @Before
24: public void before() {
25: }
26: @After
27: public void after() {
28: }
29: @Test
30: @Transactional
31: @Ignore
32: public void testSaveAllUsers() {
33: User u = new User();
34: u.setFirstName("Joy");
35: u.setLastName("Steward");
36: u.setUserName("joy");
37: u.setPassword("password");
38: userDao.persistChange(u);
39: }
40: @Test
41: public void testGetAllUser() {
42: List<User> users = (List<User>) userDao.getAllUser();
43: Assert.assertNotNull(users);
44: Assert.assertEquals(1, users.size());
45: }
46: @Test
47: public void testNamedQueryAndParam() {
48: Collection<User> users = userDao.findByNamedQueryAndParams(
49: "user.findByUserName", "joy");
50: Assert.assertNotNull(users);
51: Assert.assertEquals(1, users.size());
52: }
53: @Test
54: public void testFindUserById() {
55: User u = userDao.findById("E5429C88F74F4A8C6B13399485587401");
56: Assert.assertNotNull(u);
57: Assert.assertEquals("joy", u.getUserName());
58: }
59: }
Tuesday, May 1, 2012
Many-to-Many table relation with Join table and extra column implementation with JPA
The many to many relation in the domain modelling can be done with the extra class that has association with the many to many class. The domain modelling follow the same as in the relational model. Here is an example.
For example we have two table called "Employee" and "Project". Each Employee can work on one to many Projects and one Project can have one to many Employee. Here is the database tables
EMPLOYEE
- EMPLOYEE_ID
- EMPLOYEE_NAME
- EMPLOYEE_TYPE
PROJECT
- PROJECT_ID
- PROJECT_TITLE
- PROJECT_DURATION
EMPLOYEE_PROJECT (Join Table)
- EMPLOYEE_ID
- PROJECT_ID
- DATE-ADDED (Extra field)
Domain Modelling
Project.java
Employee.java
ProjectEmployee.java
And ProjectEmployeeId.java
The persistence-mapping.xml file looks like:
Now Create Persistence.xml file and add these:
And persistence-query.xml as :
Finally Create Test Case as follow:
That's All. Enjoy Programming..................
For example we have two table called "Employee" and "Project". Each Employee can work on one to many Projects and one Project can have one to many Employee. Here is the database tables
EMPLOYEE
- EMPLOYEE_ID
- EMPLOYEE_NAME
- EMPLOYEE_TYPE
PROJECT
- PROJECT_ID
- PROJECT_TITLE
- PROJECT_DURATION
EMPLOYEE_PROJECT (Join Table)
- EMPLOYEE_ID
- PROJECT_ID
- DATE-ADDED (Extra field)
Domain Modelling
Project.java
public class Project implements Serializable{
private static final long serialVersionUID = 2703915705484865029L;
private String projectId;
private String projectTitle;
private String projectDuration;
private List<ProjectEmployee> employees;
//getters and setters
public void addEmployee(Employee employee, Date dateAdded) {
ProjectEmployee association = new ProjectEmployee();
association.setEmployee(employee);
association.setProject(this);
association.setEmployeeId(employee.getEmployeeId());
association.setProjectId(this.getProjectId());
association.setDateAdded(dateAdded);
this.employees.add(association);
employee.getProjects().add(association);
}
}
Employee.java
public class Employee implements Serializable{
private static final long serialVersionUID = -8821659676348395539L;
private String employeeId;
private String employeeName;
private String employeeType;
private List<ProjectEmployee> projects;
}
ProjectEmployee.java
public class ProjectEmployee implements Serializable{
private static final long serialVersionUID = -2691690907714316448L;
private String employeeId;
private String projectId;
private Date dateAdded;
private Employee employee;
private Project project;
//getters and setters
}
And ProjectEmployeeId.java
public class ProjectEmployeeId implements Serializable{
private static final long serialVersionUID = 3284051729103828873L;
private String employeeId;
private String projectId;
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public int hashCode() {
return (int) (employeeId.hashCode() + projectId.hashCode());
}
public boolean equals(Object object) {
if (object instanceof ProjectEmployeeId) {
ProjectEmployeeId otherId = (ProjectEmployeeId) object;
return (otherId.getEmployeeId() == this.getEmployeeId())
&& (otherId.getProjectId() == this.getProjectId());
}
return false;
}
}
The persistence-mapping.xml file looks like:
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<entity class="Employee"
access="FIELD">
<table name="EMPLOYEE" />
<attributes>
<id name="employeeId">
<column name="EMPLOYEE_ID" />
</id>
<basic name="employeeName">
<column name="EMPLOYEE_NAME" />
</basic>
<basic name="employeeType">
<column name="EMPLOYEE_TYPE" />
</basic>
<one-to-many name="projects" fetch="LAZY" mapped-by="employee">
<cascade>
<cascade-all />
</cascade>
</one-to-many>
</attributes>
</entity>
<entity class="Project"
access="FIELD">
<table name="PROJECT" />
<attributes>
<id name="projectId">
<column name="PROJECT_ID" />
</id>
<basic name="projectTitle">
<column name="PROJECT_TITLE" />
</basic>
<basic name="projectDuration">
<column name="PROJECT_DURATION" />
</basic>
<one-to-many name="employees" fetch="LAZY" mapped-by="project">
<cascade>
<cascade-all />
</cascade>
</one-to-many>
</attributes>
</entity>
<entity class="ProjectEmployee">
<table name="EMPLOYEE_PROJECT" />
<id-class class="ProjectEmployeeId"/>
<attributes>
<id name="employeeId">
<column name="EMPLOYEE_ID"/>
</id>
<id name="projectId">
<column name="PROJECT_ID"/>
</id>
<basic name="dateAdded">
<column name="DATE_ADDED" />
</basic>
<many-to-one name="employee" id="true">
<join-column name="EMPLOYEE_ID" updatable="false" insertable="false"/>
</many-to-one>
<many-to-one name="project" id="true">
<join-column name="PROJECT_ID" updatable="false" insertable="false"/>
</many-to-one>
</attributes>
</entity>
</entity-mappings>
Now Create Persistence.xml file and add these:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="example" transaction-type="RESOURCE_LOCAL">
<mapping-file>META-INF/persistence-mapping.xml</mapping-file>
<mapping-file>META-INF/persistence-query.xml</mapping-file>
<class>Employee</class>
<class>Project</class>
<class>ProjectEmployee</class>
<class>ProjectEmployeeId</class>
<properties>
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.query.factory_class" value="org.hibernate.hql.classic.ClassicQueryTranslatorFactory"/>
<property name="hibernate.query.substitutions" value="true 1, false 0"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
</properties>
</persistence-unit>
</persistence>
And persistence-query.xml as :
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<named-query name="project.findAll">
<query>
from Project p
</query>
</named-query>
<named-query name="employee.findAll">
<query>
from Employee e;
</query>
</named-query>
<named-query name="employee.findByProject">
<query>
select e from Employee e JOIN e.projects p where p.project = ?
</query>
</named-query>
</entity-mappings>
Finally Create Test Case as follow:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext/applicationContext-*.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class ProjectDaoTest {
@Autowired
private ProjectDao projectDao;
@Autowired
private EmployeeDao employeeDao;
@Before
public void before() {
}
@After
public void after() {
}
@Test
@Transactional
public void testProjectAvailability() throws Exception{
Project p = projectDao.findByUuid("BEE9F3A7979F505EE040007F01001B21");
Employee e = new Employee();
e.setEmployeeId(UUIDGenerator.getUUID());
e.setEmployeeName("Peter");
e.setEmployeeType("Contractor");
employeeDao.persistChanges(e);
Employee e = employeeDao.findByUuid("785B9FDDD8DB56B14F13359027636041");
p.addEmployee(e, new Date());
}
@Test
public void testGetAllEmployeeFromProject() {
Project p = projectDao.findByUuid("BEE9F3A7979F505EE040007F01001B21");
List<Employee> employees = employeeDao.findByNamedQueryAndParams("employee.findByProject", p);
Assert.assertNotNull(employees);
}
}
That's All. Enjoy Programming..................
Sunday, April 22, 2012
How to integrate JSF2.0 with Spring 3.0 Framework
Steps:
1. Create the Maven Project "JSF" with
groupId: com.jsf.app
artifactId: jsf
package: war
and add following dependencies in pom.xml
2. Create the directory structure like:
jsf
-src
--main
---java
-----com
-------jsf
--------app
----------managedbean
-------------UserBean.java
----------service
-------------UserService.java
-------------impl
---------------UserServiceImpl.java
---resources
----applicationContext.xml
----log4j.xml
----messages.properties
---webapp
-----pages
-------jsfspring.xhtml
-----WEB-INF
--------faces-config.xml
--------web.xml
--test
--pom.xml
3. In web.xml file add these settings.
4.Create new JSF bean name as UserBean as shown below in com.jsf.app.managedbean package
5. Next create Spring Interface and Implementation in com.jsf.app.service and com.jsf.app.service.impl package respectively:
6. Now Create Faces-Config.xml with following information in WEB-INF folder:
7. Also Create the applicationContext.xml in resources folder:
8. Now create the jsf page in the webapp/pages/ folder as shown below:
9. Finally add the Log4j.xml file for logging purpose inside the resources folder as shown in below:
10. Finally to run the application, right click the project->maven->maven clean,
again right click project->maven->maven install, this will create the war file.
Take a war file and deploy in the tomcat server and run the server as:
1. Create the Maven Project "JSF" with
groupId: com.jsf.app
artifactId: jsf
package: war
and add following dependencies in pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jsf.app</groupId>
<artifactId>jsf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>jsf</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.bom.version>3.1.0.RELEASE</org.springframework.bom.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Logging Dependencies -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<!-- http://download.java.net/maven/2 -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.0-b03</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.0-b03</version>
</dependency>
<!-- http://repo1.maven.org/maven -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.el</groupId>
<artifactId>el-ri</artifactId>
<version>1.0</version>
</dependency>
<!-- Spring Related Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.bom.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.bom.version}</version>
</dependency>
</dependencies>
</project>
2. Create the directory structure like:
jsf
-src
--main
---java
-----com
-------jsf
--------app
----------managedbean
-------------UserBean.java
----------service
-------------UserService.java
-------------impl
---------------UserServiceImpl.java
---resources
----applicationContext.xml
----log4j.xml
----messages.properties
---webapp
-----pages
-------jsfspring.xhtml
-----WEB-INF
--------faces-config.xml
--------web.xml
--test
--pom.xml
3. In web.xml file add these settings.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>JavaServerFaces&Spring</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CONFIG-FILES</param-name>
<param-value>WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>pages/jsfspring.xhtml</welcome-file>
</welcome-file-list>
</web-app>
4.Create new JSF bean name as UserBean as shown below in com.jsf.app.managedbean package
package com.jsf.app.managedbean;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.jsf.app.service.UserService;
@Component("userBean")
@Scope("session")
public class UserBean {
private static final Logger logger = Logger.getLogger(UserBean.class
.getName());
@Autowired
@Qualifier("userService")
public UserService userService;
public String getPrintMsgFromSpring() {
logger.info("Invoking UserService");
return userService.getMessage();
}
}
5. Next create Spring Interface and Implementation in com.jsf.app.service and com.jsf.app.service.impl package respectively:
package com.jsf.app.service;
public interface UserService {
public String getMessage();
}
package com.jsf.app.service.impl;
import org.springframework.stereotype.Service;
import com.jsf.app.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
private String name = "Voila!";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getMessage() {
return "JSF - Spring Integrtion " + name;
}
}
6. Now Create Faces-Config.xml with following information in WEB-INF folder:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<resource-bundle>
<base-name>messages</base-name>
<var>msg</var>
</resource-bundle>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
7. Also Create the applicationContext.xml in resources folder:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.jsf.app.managedbean,com.jsf.app.service" />
</beans>
8. Now create the jsf page in the webapp/pages/ folder as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h1>JSF 2.0 + Spring Example</h1>
#{userBean.printMsgFromSpring}
</h:body>
</html>
9. Finally add the Log4j.xml file for logging purpose inside the resources folder as shown in below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<!-- <param name="ConversionPattern" value="[%d{ISO8601}] %-5p [%c] %m %n" /> -->
<param name="ConversionPattern" value="%-5p [%c] %m %n" />
</layout>
</appender>
<appender name="STDERR" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.err" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{ISO8601}] %-5p [%c] %m %n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="ERROR" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
<appender name="ROLLING_FILE" class="org.apache.log4j.RollingFileAppender">
<!-- param name="File" value="c:/logs/miis30.log" /-->
<param name="File" value="jsf.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="5120KB" />
<param name="MaxBackupIndex" value="5" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{ISO8601}] %-5p %m%n" />
</layout>
</appender>
<root>
<level value="ERROR" />
<appender-ref ref="STDERR" />
</root>
<root>
<level value="DEBUG" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
10. Finally to run the application, right click the project->maven->maven clean,
again right click project->maven->maven install, this will create the war file.
Take a war file and deploy in the tomcat server and run the server as:
http://localhost:8088/jsf/pages/jsfspring.xhtml
Tuesday, March 6, 2012
Java J2EE Interview Questions Part 2
15. How do we test private methods in JUnit?
- Private methods cannot be directly tested. If required we can use Java Reflection to test private methods.
16. How do we test protected methods?
- Place the test class under the same package as the class under test.
17. How do you invoke Stored Procedure from Hibernate?
- use hibernate 3 annotation as:
@NamedNativeQueries({
@NamedNativeQuery(
name = "callStockStoreProcedure",
query = "CALL GetStocks(:stockCode)",
resultClass = Stock.class
)
})
Query query = session.getNamedQuery("callStockStoreProcedure")
.setParameter("stockCode", "7277");
18. How do you manage transaction in Spring using Hibernate?
- Declare HibernateTransactionManager and set dataSource and sessionFactory property
- Create TransactionInterceptor and set transactionManager and transactionAttributes
- Now create ProxyFactoryBean and set the target dao/bo bean and interceptorNames
19. How do you configure connection pooling using JDBC?
-
20. How to create store procedure in oracle?
CREATE OR REPLACE PROCEDURE my_store_procedure
IS
BEGIN
select * from my_table where uid = n;
END;
21. What is the difference between LinkList and ArrayList?
22. What is the difference between forward and send redirect?
23. What is MVC?
- Private methods cannot be directly tested. If required we can use Java Reflection to test private methods.
16. How do we test protected methods?
- Place the test class under the same package as the class under test.
17. How do you invoke Stored Procedure from Hibernate?
- use hibernate 3 annotation as:
@NamedNativeQueries({
@NamedNativeQuery(
name = "callStockStoreProcedure",
query = "CALL GetStocks(:stockCode)",
resultClass = Stock.class
)
})
Query query = session.getNamedQuery("callStockStoreProcedure")
.setParameter("stockCode", "7277");
18. How do you manage transaction in Spring using Hibernate?
- Declare HibernateTransactionManager and set dataSource and sessionFactory property
- Create TransactionInterceptor and set transactionManager and transactionAttributes
- Now create ProxyFactoryBean and set the target dao/bo bean and interceptorNames
19. How do you configure connection pooling using JDBC?
-
20. How to create store procedure in oracle?
CREATE OR REPLACE PROCEDURE my_store_procedure
IS
BEGIN
select * from my_table where uid = n;
END;
21. What is the difference between LinkList and ArrayList?
22. What is the difference between forward and send redirect?
23. What is MVC?
In progress...........
Sunday, March 4, 2012
Java J2EE Interview Questions Part 1
1. What are the new features in JDK or Java 6?
- XML and Web Services support
- JDBC 4.0 support
- More Annotation type
- More flexible annotation processing
- Java compiler API accessible from programs
- Application client GUI enhancements for both AWT and Swing.
- Scripting support.
- Security like XML-Digital Signature APIs.
2. What is Java reflection?
- Java's reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the name of the classes, methods etc at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. Board use of Java Reflection is: security, code complexity, run time performance etc. Other tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool.
3. What is synchronization?
- With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. this usually leads to significant errors.
4. What is volatile in Java?
- volatile is keyword and value of the volatile variable will never be cached thread-locally (i.e. all reads and writes will go straight to main memory).
- also access to the variable acts as though it is enclosed in a synchronized block.
5. How do you improve performance of the database query? or How do you performance tune your database?
- denormalize the table where appropriate.
- proper use of index columns (eg index based on numeric fields than character columns)
- reduce number of columns that make up a composite key
- proper partitioning of tablespace and create special tablespace for CLOB, BLOG
- data access performance can be tuned by store procedure reducing network overhead and also caching data within your application
6. What is Hibernate dirty checking?
- Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. Hence, it automatically update only those fields which has been modified. As opposed to updating all persistent objects at the end of each work, automatic dirty checking can offer significant performance savings.
7. What is SOAP fault?
- SOAP fault is an error in a SOAP communication resulting from incorrect message format, header-processing problems, or incompatibility between appliaiton. when a SOAP fault occurs, a special message is generated that contains data indicating where the error originated and what caused it. This data is called a fault element. A message that includes a fault element is known as a fault message.
8. What is the difference between SOAP and RESTful web services?
- Use SOAP when
1. required stateful operations
2. required more formal contracts
3. required asynchronous processing and invocation
- Use RESTful when
1. required limited bandwidth and resources
2. required totally stateless operations
3. required caching situations
9. What is the difference between JDBC excecute(), executeQuery() and executeUpdate()?
- execute statement is prepared statement which is kind of SQL statement. signature boolean execute().
- executeQuery statement is prepared statement to execute SQL Query and returns ResultSet. signature ResultSet executeQuery().
- executeUpdate is prepared statement for insert, update, delete and returns nothing. signature int executeUpdate().
10. What is the prepared and callable statement in JDBC?
- Prepared Statement is precompiled SQL Statement and accept parameters, more faster than regular statement and secure for SQL Injection.
- Callable Statement is for calling Stored Procedure.
11. What happen to the JMS message when MOM is down?
- message delivery mode set to durable (persistent) when MOM save message to database incase of server crash or message lost and it has adverse effect on performance, but ensure that message delivery is guaranteed.
12. How will you map class inheritance to relational data model?
- Map class hierarchy to single database table (union mapping)
- Map each class to its own table (vertical mapping)
- Map each concrete class to its own table (horizontal mapping)
13. What is the difference between throw and throws in Java?
- throws declare the exception for the method like:
public void myMethod() throws MyException{} //tells us that what method might pass back to the caller.
- while throw actually throw the exception like:
public void myMethod() throws MyException{
if(condition) {
throw new MyException("throw exception"); // tells us to throw MyException to the caller.
}
}
14. How will you control two concurrent transactions accessing a database?
- use isolation levels. Dirty read, Norepeatable read and Phantom reads. Provide different isolation levels like:
TRANSACTION_READ_UNCOMMITED, TRANSACTION_READ_COMMITED, TRANSACTION_REPEATABLE_READ, and TRANSACTION_SERIALIZABLE.
- XML and Web Services support
- JDBC 4.0 support
- More Annotation type
- More flexible annotation processing
- Java compiler API accessible from programs
- Application client GUI enhancements for both AWT and Swing.
- Scripting support.
- Security like XML-Digital Signature APIs.
2. What is Java reflection?
- Java's reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the name of the classes, methods etc at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. Board use of Java Reflection is: security, code complexity, run time performance etc. Other tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool.
3. What is synchronization?
- With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. this usually leads to significant errors.
4. What is volatile in Java?
- volatile is keyword and value of the volatile variable will never be cached thread-locally (i.e. all reads and writes will go straight to main memory).
- also access to the variable acts as though it is enclosed in a synchronized block.
5. How do you improve performance of the database query? or How do you performance tune your database?
- denormalize the table where appropriate.
- proper use of index columns (eg index based on numeric fields than character columns)
- reduce number of columns that make up a composite key
- proper partitioning of tablespace and create special tablespace for CLOB, BLOG
- data access performance can be tuned by store procedure reducing network overhead and also caching data within your application
6. What is Hibernate dirty checking?
- Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. Hence, it automatically update only those fields which has been modified. As opposed to updating all persistent objects at the end of each work, automatic dirty checking can offer significant performance savings.
7. What is SOAP fault?
- SOAP fault is an error in a SOAP communication resulting from incorrect message format, header-processing problems, or incompatibility between appliaiton. when a SOAP fault occurs, a special message is generated that contains data indicating where the error originated and what caused it. This data is called a fault element. A message that includes a fault element is known as a fault message.
8. What is the difference between SOAP and RESTful web services?
- Use SOAP when
1. required stateful operations
2. required more formal contracts
3. required asynchronous processing and invocation
- Use RESTful when
1. required limited bandwidth and resources
2. required totally stateless operations
3. required caching situations
9. What is the difference between JDBC excecute(), executeQuery() and executeUpdate()?
- execute statement is prepared statement which is kind of SQL statement. signature boolean execute().
- executeQuery statement is prepared statement to execute SQL Query and returns ResultSet. signature ResultSet executeQuery().
- executeUpdate is prepared statement for insert, update, delete and returns nothing. signature int executeUpdate().
10. What is the prepared and callable statement in JDBC?
- Prepared Statement is precompiled SQL Statement and accept parameters, more faster than regular statement and secure for SQL Injection.
- Callable Statement is for calling Stored Procedure.
11. What happen to the JMS message when MOM is down?
- message delivery mode set to durable (persistent) when MOM save message to database incase of server crash or message lost and it has adverse effect on performance, but ensure that message delivery is guaranteed.
12. How will you map class inheritance to relational data model?
- Map class hierarchy to single database table (union mapping)
- Map each class to its own table (vertical mapping)
- Map each concrete class to its own table (horizontal mapping)
13. What is the difference between throw and throws in Java?
- throws declare the exception for the method like:
public void myMethod() throws MyException{} //tells us that what method might pass back to the caller.
- while throw actually throw the exception like:
public void myMethod() throws MyException{
if(condition) {
throw new MyException("throw exception"); // tells us to throw MyException to the caller.
}
}
14. How will you control two concurrent transactions accessing a database?
- use isolation levels. Dirty read, Norepeatable read and Phantom reads. Provide different isolation levels like:
TRANSACTION_READ_UNCOMMITED, TRANSACTION_READ_COMMITED, TRANSACTION_REPEATABLE_READ, and TRANSACTION_SERIALIZABLE.
Subscribe to:
Posts (Atom)