To set up tomcat server in debug mode add the following line in the VM argument
Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
In eclipse configuration you can add the Edit configuration window as shown below:
Prabin's Blog
Thursday, March 14, 2013
Setting Maximum Perm Size for JVM
Maximun Perm Memory is the memory where most of the classes and class loader reside. To adjust or increment the maximum perm gen size, just add the following line as VM arguments when starting server.
XX:MaxPermSize=256m
Where 256 is the memory MB, you can adjust this value as per your application requirement.
XX:MaxPermSize=256m
Where 256 is the memory MB, you can adjust this value as per your application requirement.
Sunday, July 15, 2012
Reading file in Java
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();
}
}
}
}
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();
}
}
}
}
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..................
Subscribe to:
Posts (Atom)