Download js-1.6R7.jar from net. Or you can use this pom.xml to download this jar file
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.6R7 </version>
</dependency>
How to setup rhino js in console:
I have put my this above jar into D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar
creat one bat file like rhino.bat and put this command
java -classpath .;D:\.m2\repository\rhino\js\1.6R7\js-1.6R7.jar org.mozilla.javascript.tools.shell.Main
save it.
Now double click on that batch file you will get
js> prompt.
now you can check bit code here
js> print('Binod')
Binod
js> 37+57
94
js>
for quiting:
quit();
js> quit();
You can open windows application using js
js> runCommand("notepad"); // It will open notepad
0
js> runCommand("mspaint");
0
js> runCommand("calc");
0
js> runCommand("cmd", "/C", "date /T")
Fri 08/13/2010
create one java script like abc.js
function check(name) {
for(i=0;i<10;i++){
print(name);
}
}
js> load("abc.js");
js> check("Binod");
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
Binod
js>
How to use the Rhino javascript embedded into java code
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* @author Binod Suman
*/
public class Demo {
public static void main(String[] args) {
new Demo().check();
}
public void check(){
ScriptEngineManager engineMgr = new ScriptEngineManager();
ScriptEngine engine = engineMgr.getEngineByName("JavaScript");
try {
engine.eval("function sayHello(s,c) {" +" println('Hello, world! '+s+' '+c);" +"}");
Invocable invocableEngine = (Invocable) engine;
invocableEngine.invokeFunction("sayHello","Binod","Tecnotree");
} catch (ScriptException ex) { ex.printStackTrace();}
catch(Exception e){e.printStackTrace();}
}
}
Useful link:
http://www.mozilla.org/rhino/tutorial.html
Good Tutorial : http://www.mozilla.org/rhino/ScriptingJava.html
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/
Sunday, August 15, 2010
Tuesday, July 13, 2010
Null value was assigned to a property of primitive type setter of
While fetching data from database using jpa and hibernate I got one error and this is
org.springframework.orm.jpa.JpaSystemException: org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.ayush.suman.bo.Address.trusted; nested exception is javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.ayush.suman.bo.Address.trusted
My Address.java was like this:
@Entity
@Table(name="address")
public class Address {
@Id
private long id;
private String address;
@Column(name="country_code")
private String countryCode;
@Column(name="address_type")
private String addressType;
private int trusted;
with getter and setter methods
}
Solution:
Just change int to Integer simple ....... :)
Now updated Address.java
@Table(name="address")
public class Address {
@Id
private long id;
private String address;
@Column(name="country_code")
private String countryCode;
@Column(name="address_type")
private String addressType;
private Integer trusted;
with getter and setter methods
}
Dont forgate to change int to Integer in setter and getter method of trusted field.
org.springframework.orm.jpa.JpaSystemException: org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.ayush.suman.bo.Address.trusted; nested exception is javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.ayush.suman.bo.Address.trusted
My Address.java was like this:
@Entity
@Table(name="address")
public class Address {
@Id
private long id;
private String address;
@Column(name="country_code")
private String countryCode;
@Column(name="address_type")
private String addressType;
private int trusted;
with getter and setter methods
}
Solution:
Just change int to Integer simple ....... :)
Now updated Address.java
@Table(name="address")
public class Address {
@Id
private long id;
private String address;
@Column(name="country_code")
private String countryCode;
@Column(name="address_type")
private String addressType;
private Integer trusted;
with getter and setter methods
}
Dont forgate to change int to Integer in setter and getter method of trusted field.
Turning off hibernate logging console output, How to hide/disable Hibernate log to console
Just sharing my experiance with Hibernate 3.0.
Even after using the log4j.xml with
<logger name="org.hibernate">
<level value="info"/>
</logger>
I could not able to trun off the huge hibernate log on console, it was coming like this:
7 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.4.0.GA
37 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.0.SP1
43 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
48 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
52 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
163 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.1.0.GA
168 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.4.0.GA
202 [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
name: VMSPersistenceUnit
...]
Finally I got solution and that is here:
Just add slf4j-log4j12-1.5.2.jar in your classpath if you are using slf4j-api. Actually SLF4J is used by hibernate and if you are using log4j you need to setup the bridge for your logging system.
In my case, I have these jar files in my project classpath:
slf4j-api-1.5.6.jar
slf4j-log4j12-1.5.6.jar
slf4j-simple-1.4.2.jar
Thats it ...... :)
Even after using the log4j.xml with
<logger name="org.hibernate">
<level value="info"/>
</logger>
I could not able to trun off the huge hibernate log on console, it was coming like this:
7 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.4.0.GA
37 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.0.SP1
43 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
48 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
52 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
163 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.1.0.GA
168 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.4.0.GA
202 [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
name: VMSPersistenceUnit
...]
Finally I got solution and that is here:
Just add slf4j-log4j12-1.5.2.jar in your classpath if you are using slf4j-api. Actually SLF4J is used by hibernate and if you are using log4j you need to setup the bridge for your logging system.
In my case, I have these jar files in my project classpath:
slf4j-api-1.5.6.jar
slf4j-log4j12-1.5.6.jar
slf4j-simple-1.4.2.jar
Thats it ...... :)
Monday, June 14, 2010
Check small java code on groovy console
For this tutorial, Groovy should be installed to your pc.
For how to install Groovy and fundamental of Groovy, check here.
http://ayushsuman.blogspot.com/2010/04/groovy-getting-started-how-use-groovy.html
If you want to check some java code then no need to write the one complete java class to check you bit code.You can use groovy console to check your java codes.
If you have already configured your groovy bin folder with path then
c:\>groovyConsole.bat
It will open one window then you can paste your code
String name = "BINOD KUMAR SUMAN";
System.out.println("Name :: "+name);
System.out.println("Now :: "+new Date());
and press Ctrl+R and see your code result on below screen.
Name :: BINOD KUMAR SUMAN
Now :: Sat Jun 12 11:28:02 EEST 2010
Ctrl+W for clear the output. Again you can check your some code. :)
For how to install Groovy and fundamental of Groovy, check here.
http://ayushsuman.blogspot.com/2010/04/groovy-getting-started-how-use-groovy.html
If you want to check some java code then no need to write the one complete java class to check you bit code.You can use groovy console to check your java codes.
If you have already configured your groovy bin folder with path then
c:\>groovyConsole.bat
It will open one window then you can paste your code
String name = "BINOD KUMAR SUMAN";
System.out.println("Name :: "+name);
System.out.println("Now :: "+new Date());
and press Ctrl+R and see your code result on below screen.
Name :: BINOD KUMAR SUMAN
Now :: Sat Jun 12 11:28:02 EEST 2010
Ctrl+W for clear the output. Again you can check your some code. :)
Get the fild value from java class during run time using reflection
Get the fild value from java class during run time using reflection.
Suppose, you have one java class that is having a lot of static value and you want that int value during run time with dynamic field name.
Like,
public class Types
{
public static final int BIT = -7;
public static final int TINYINT = -6;
public static final int SMALLINT = 5;
public static final int INTEGER = 4;
public static final int BIGINT = -5;
public static final int FLOAT = 6;
public static final int REAL = 7;
public static final int DOUBLE = 8;
public static final int NUMERIC = 2;
public static final int DECIMAL = 3;
public static final int CHAR = 1;
public static final int VARCHAR = 12;
public static final int LONGVARCHAR = -1;
public static final int DATE = 91;
public static final int TIME = 92;
public static final int TIMESTAMP = 93;
}
And you have one string that containg the "TINYINT" during run time, now you have to fetch what is the value of TINYINT dynamically.
string filed = "TINYINT";
String field = "TINYINT";
Class typeClass = Class.forName("java.sql.Types");
int fieldValue = (Integer) typeClass.getField(field).get(null);
System.out.println("fieldValue :: "+fieldValue);
Output:
fieldValue :: -6
Suppose, you have one java class that is having a lot of static value and you want that int value during run time with dynamic field name.
Like,
public class Types
{
public static final int BIT = -7;
public static final int TINYINT = -6;
public static final int SMALLINT = 5;
public static final int INTEGER = 4;
public static final int BIGINT = -5;
public static final int FLOAT = 6;
public static final int REAL = 7;
public static final int DOUBLE = 8;
public static final int NUMERIC = 2;
public static final int DECIMAL = 3;
public static final int CHAR = 1;
public static final int VARCHAR = 12;
public static final int LONGVARCHAR = -1;
public static final int DATE = 91;
public static final int TIME = 92;
public static final int TIMESTAMP = 93;
}
And you have one string that containg the "TINYINT" during run time, now you have to fetch what is the value of TINYINT dynamically.
string filed = "TINYINT";
String field = "TINYINT";
Class typeClass = Class.forName("java.sql.Types");
int fieldValue = (Integer) typeClass.getField(field).get(null);
System.out.println("fieldValue :: "+fieldValue);
Output:
fieldValue :: -6
Tuesday, June 8, 2010
First Struts Example with Hibernate, Hibernate and Spring first example
1. Create one MyFirstStruts Web Dynamic Project (Say C:\workspaceAll\Struts\FirstStruts)
2. Create JSP pages
a) CustomerForm.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent)
b) Success.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent\Success.jsp)
3. Configuration Files
a) web.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\web.xml)
b) struts-config.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-config.xml)
c) hibernate.cfg.xml (C:\workspaceAll\Struts\MyFirstStruts\src\hibernate.cfg.xml)
d) Customer.hbm.xml (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.hbm.xml)
4. Java Files
a) CustomerForm.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerForm.java)
b) CustomerAction.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerAction.java)
c)Customer.java (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.java)
5. Put these jar files (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\lib)
a) commons-beanutils.jar
b) commons-collections.jar
c) commons-digester.jar
d) commons-logging.jar
e) struts.jar
f) mysql-connector-java-3.1.12-bin.jar
g) commons-logging-1.1.jar
h) dom4j-1.6.1.jar
i) commons-collections-3.2.jar
j) log4j-1.2.15.jar
k) slf4j-1.6.0/slf4j-1.6.0/slf4j-api-1.6.0.jar
l) slf4j-1.6.0/slf4j-1.6.0/slf4j-log4j12-1.6.0.jar
m) slf4j-1.6.0/slf4j-1.6.0/slf4j-simple-1.6.0.jar
n) javassist-3.3.jar
o) jta-1.0.1B.jar
p) hibernate-commons-annotations-3.1.0.GA.jar
q) hibernate-annotations-3.1beta8.jar
r) hibernate-core-3.3.1.GA.jar
s) antlr-2.7.5H3.jar
6. Download and put struts-html.tld into C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-html.tld
(If you download struts-1.2.9-lib.zip, then struts-html.tld file is there)
CustomerForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html xhtml="true">
<body>
<html:form action="/submitCustomerForm">
Put Customer First Name <html:text property="firstName" size="16" maxlength="16"/> <BR/>
Put Customer Last Name <html:text property="lastName" size="16" maxlength="16"/> <BR/> <P/>
<html:submit>Save</html:submit>
</html:form>
</body>
</html:html>
Success.jsp
<html>
<h1> THIS IS SUCCESS PAGE </h1>
</html>
CustomerForm.java
import org.apache.struts.action.ActionForm;
public class CustomerForm extends ActionForm {
private String firstName;
private String lastName;
public CustomerForm() { firstName = ""; lastName = ""; }
public String getFirstName() { return firstName; }
public void setFirstName(String s) { this.firstName = s; }
public String getLastName() { return lastName; }
public void setLastName(String s) { this.lastName = s; }
}
Customer.java
/**
* @author Binod Suman
*/
public class Customer {
private int custId;
private String firstName;
private String lastName;
public Customer(){}
public int getCustId() {return custId;}
public void setCustId(int custId) {this.custId = custId;}
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
}
CustomerAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class CustomerAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionForward nextPage = null;
CustomerForm custForm = (CustomerForm) form;
String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
saveCustomer(customer);
System.out.println("Customer First name is " + firstName);
System.out.println("Customer Last name is " + lastName);
nextPage = mapping.findForward("success");
return nextPage; }
public void saveCustomer(Customer customer){
System.out.println("Inserting new customer record ...... ");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(customer);
transaction.commit();
session.flush();
session.close();
System.out.println("Customer record has been successfully saved ");
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello World Struts Application</display-name>
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-
name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <taglib-uri>/WEB-INF/struts-
html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app>
struts-config.xml
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <form-beans> <form-bean name="myForm" type="CustomerForm" /> </form-beans>
<action-mappings> <action path="/submitCustomerForm" type="CustomerAction" name="myForm" scope="request"> <forward name="success" path="/Success.jsp" />
</action> </action-mappings>
</struts-config>
create table in mysql sumandb database.
CREATE TABLE customer (
id int(11) NOT NULL,
firstName varchar(100) default NULL,
secondName varchar(100) default NULL,
PRIMARY KEY (id)
)
Start the server after deploy your application:
http://localhost:8080/FirstStruts/CustomerForm.jsp
Put First Name: Binod
Put Second Name: Suman
Click on Save button and check the server console, you should be get
Customer First name is Binod
Customer Last name is Suman
Check your sumandb database, one new record has been inserted.
and new success page will come with message:
THIS IS SUCCESS PAGE
2. Create JSP pages
a) CustomerForm.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent)
b) Success.jsp (C:\workspaceAll\Struts\MyFirstStruts\WebContent\Success.jsp)
3. Configuration Files
a) web.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\web.xml)
b) struts-config.xml (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-config.xml)
c) hibernate.cfg.xml (C:\workspaceAll\Struts\MyFirstStruts\src\hibernate.cfg.xml)
d) Customer.hbm.xml (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.hbm.xml)
4. Java Files
a) CustomerForm.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerForm.java)
b) CustomerAction.java (C:\workspaceAll\Struts\MyFirstStruts\src\CustomerAction.java)
c)Customer.java (C:\workspaceAll\Struts\MyFirstStruts\src\Customer.java)
5. Put these jar files (C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\lib)
a) commons-beanutils.jar
b) commons-collections.jar
c) commons-digester.jar
d) commons-logging.jar
e) struts.jar
f) mysql-connector-java-3.1.12-bin.jar
g) commons-logging-1.1.jar
h) dom4j-1.6.1.jar
i) commons-collections-3.2.jar
j) log4j-1.2.15.jar
k) slf4j-1.6.0/slf4j-1.6.0/slf4j-api-1.6.0.jar
l) slf4j-1.6.0/slf4j-1.6.0/slf4j-log4j12-1.6.0.jar
m) slf4j-1.6.0/slf4j-1.6.0/slf4j-simple-1.6.0.jar
n) javassist-3.3.jar
o) jta-1.0.1B.jar
p) hibernate-commons-annotations-3.1.0.GA.jar
q) hibernate-annotations-3.1beta8.jar
r) hibernate-core-3.3.1.GA.jar
s) antlr-2.7.5H3.jar
6. Download and put struts-html.tld into C:\workspaceAll\Struts\MyFirstStruts\WebContent\WEB-INF\struts-html.tld
(If you download struts-1.2.9-lib.zip, then struts-html.tld file is there)
CustomerForm.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html xhtml="true">
<body>
<html:form action="/submitCustomerForm">
Put Customer First Name <html:text property="firstName" size="16" maxlength="16"/> <BR/>
Put Customer Last Name <html:text property="lastName" size="16" maxlength="16"/> <BR/> <P/>
<html:submit>Save</html:submit>
</html:form>
</body>
</html:html>
Success.jsp
<html>
<h1> THIS IS SUCCESS PAGE </h1>
</html>
CustomerForm.java
import org.apache.struts.action.ActionForm;
public class CustomerForm extends ActionForm {
private String firstName;
private String lastName;
public CustomerForm() { firstName = ""; lastName = ""; }
public String getFirstName() { return firstName; }
public void setFirstName(String s) { this.firstName = s; }
public String getLastName() { return lastName; }
public void setLastName(String s) { this.lastName = s; }
}
Customer.java
/**
* @author Binod Suman
*/
public class Customer {
private int custId;
private String firstName;
private String lastName;
public Customer(){}
public int getCustId() {return custId;}
public void setCustId(int custId) {this.custId = custId;}
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
}
CustomerAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class CustomerAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionForward nextPage = null;
CustomerForm custForm = (CustomerForm) form;
String firstName = custForm.getFirstName();
String lastName = custForm.getLastName();
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
saveCustomer(customer);
System.out.println("Customer First name is " + firstName);
System.out.println("Customer Last name is " + lastName);
nextPage = mapping.findForward("success");
return nextPage; }
public void saveCustomer(Customer customer){
System.out.println("Inserting new customer record ...... ");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(customer);
transaction.commit();
session.flush();
session.close();
System.out.println("Customer record has been successfully saved ");
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Hello World Struts Application</display-name>
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-
name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <taglib-uri>/WEB-INF/struts-
html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app>
struts-config.xml
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <form-beans> <form-bean name="myForm" type="CustomerForm" /> </form-beans>
<action-mappings> <action path="/submitCustomerForm" type="CustomerAction" name="myForm" scope="request"> <forward name="success" path="/Success.jsp" />
</action> </action-mappings>
</struts-config>
create table in mysql sumandb database.
CREATE TABLE customer (
id int(11) NOT NULL,
firstName varchar(100) default NULL,
secondName varchar(100) default NULL,
PRIMARY KEY (id)
)
Start the server after deploy your application:
http://localhost:8080/FirstStruts/CustomerForm.jsp
Put First Name: Binod
Put Second Name: Suman
Click on Save button and check the server console, you should be get
Customer First name is Binod
Customer Last name is Suman
Check your sumandb database, one new record has been inserted.
and new success page will come with message:
THIS IS SUCCESS PAGE
How to use preapredStatment using Spring JdbcOperations.
Even it is very small thing but I searched on net lot with these words on goolge but didnt get solution.
Now I am going to show here how we can use preaparedstatement with spring JdbcOperations.
Create these five file in your Eclipse project.
DaoOperation.java
IDaoOperation.java
App.java
Myconfig.xml
MyProperties.properties
DaoOperation.java
import java.sql.SQLException;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcOperations;
public class DaoOperation implements IDaoOperation{
private JdbcOperations jdbc;
public void saveStudentData() throws SQLException{
String sql = "insert into student (id,name,marks) values (?,?,?)";
Object[] args = {5,"Suman",99};
executeUdpdateSQL(sql,args);
}
public void updateStudentData() throws SQLException{
String sql = "update student set name=?, marks = ? where id = ?";
Object[] args = {"Ayush Suman",999,5};
executeUdpdateSQL(sql,args);
}
public void executeUdpdateSQL(String sql, Object[] args) throws SQLException {
jdbc.update(sql, args);
}
public JdbcOperations getJdbc() {return jdbc;}
public void setJdbc(JdbcOperations jdbc) {this.jdbc = jdbc;}
}
IDaoOperation.java
import java.sql.SQLException;
/**
* @author Binod Suman
*/
public interface IDaoOperation {
public void saveStudentData() throws SQLException;
public void updateStudentData() throws SQLException;
}
App.java
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) throws Exception {
IDaoOperation daoOperation;
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Myconfig.xml");
daoOperation = (IDaoOperation) context.getBean("daoOperation");
daoOperation.saveStudentData();
// daoOperation.updateStudentData();
}
}
Myconfig.xml
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:mbean-server/>
<context:property-placeholder location="classpath:/MyProperties.properties"/>
<bean id="daoOperation" class="DaoOperation"
p:jdbc-ref="jdbc" />
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" />
</beans>
MyProperties.properties
db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost/sumandb
db.username = root
db.password = mysql
Now I am going to show here how we can use preaparedstatement with spring JdbcOperations.
Create these five file in your Eclipse project.
DaoOperation.java
IDaoOperation.java
App.java
Myconfig.xml
MyProperties.properties
DaoOperation.java
import java.sql.SQLException;
import java.util.Set;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcOperations;
public class DaoOperation implements IDaoOperation{
private JdbcOperations jdbc;
public void saveStudentData() throws SQLException{
String sql = "insert into student (id,name,marks) values (?,?,?)";
Object[] args = {5,"Suman",99};
executeUdpdateSQL(sql,args);
}
public void updateStudentData() throws SQLException{
String sql = "update student set name=?, marks = ? where id = ?";
Object[] args = {"Ayush Suman",999,5};
executeUdpdateSQL(sql,args);
}
public void executeUdpdateSQL(String sql, Object[] args) throws SQLException {
jdbc.update(sql, args);
}
public JdbcOperations getJdbc() {return jdbc;}
public void setJdbc(JdbcOperations jdbc) {this.jdbc = jdbc;}
}
IDaoOperation.java
import java.sql.SQLException;
/**
* @author Binod Suman
*/
public interface IDaoOperation {
public void saveStudentData() throws SQLException;
public void updateStudentData() throws SQLException;
}
App.java
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) throws Exception {
IDaoOperation daoOperation;
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Myconfig.xml");
daoOperation = (IDaoOperation) context.getBean("daoOperation");
daoOperation.saveStudentData();
// daoOperation.updateStudentData();
}
}
Myconfig.xml
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:mbean-server/>
<context:property-placeholder location="classpath:/MyProperties.properties"/>
<bean id="daoOperation" class="DaoOperation"
p:jdbc-ref="jdbc" />
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" />
</beans>
MyProperties.properties
db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost/sumandb
db.username = root
db.password = mysql
Sunday, June 6, 2010
First Hibernate example, Hibernate getting started
No need to explain about Hibernate as it is well known ORM tool.
One simple running example I am going to explain here. Just you follow step by step you would be able to run your first Hibernate example. This example will contect mysql database.
1. Download all below jar file.
mysql-connector-java-3.1.12-bin.jar
commons-logging-1.1.jar
dom4j-1.6.1.jar
commons-collections-3.2.jar
log4j-1.2.15.jar
slf4j-api-1.6.0.jar
slf4j-log4j12-1.6.0.jar
slf4j-simple-1.6.0.jar
javassist-3.3.jar
jta-1.0.1B.jar
hibernate-commons-annotations-3.1.0.GA.jar
hibernate-annotations-3.1beta8.jar
hibernate-core-3.3.1.GA.jar
antlr-2.7.5H3.jar
javassist-3.3.jar
2. First create one project in Eclipse say FirstHibernate and add these jar file into that project.
3. Create these below three file into your project src folder.
hibernate.cfg.xml
Student.hbm.xml
Student.java
Client.java
create one student table in database. In our example database name is sumandb.
CREATE TABLE student (
id int(11) NOT NULL,
name varchar(90) default NULL,
marks int(11) default NULL,
PRIMARY KEY (id)
)
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost/sumandb</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping files -->
<mapping resource="Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="Student" table="student">
<id name="studentId" column="id">
<generator class="increment" />
</id>
<!-- Both property are optional here as property name and column name are same -->
<property name="name" column="name" />
<property name="marks" column="marks" />
</class>
</hibernate-mapping>
Student.java
/**
* @author Binod Suman
*/
public class Student {
private int studentId;
private String name;
private int marks;
public Student() { }
public Student(int studentId, String name, int marks) {
this.studentId = studentId;
this.name = name;
this.marks = marks;
}
public Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
public int getStudentId() {return studentId;}
public void setStudentId(int studentId) {this.studentId = studentId;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getMarks() {return marks;}
public void setMarks(int marks) {this.marks = marks;}
}
Client.java
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
/*
* @author Binod Suman
*/
public class Client {
public static void main(String[] args) {
Client test = new Client();
test.saveStudent();
// test.showAllStudent();
// test.searchStudent(2);
}
public void saveStudent(){
System.out.println("Inserting new Student record ...... ");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Student student = new Student("Binod Suman",99);
session.save(student);
transaction.commit();
session.flush();
session.close();
System.out.println("Student record has been successfully saved ");
}
public void showAllStudent(){
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
List
for(Student student : students){
System.out.println("Student Name :: "+student.getName());
System.out.println("Student Roll :: "+student.getStudentId());
System.out.println("Student Marks :: "+student.getMarks());
System.out.println("************************");
}
}
public void searchStudent(int id){
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
Student student = (Student)session.load(Student.class, id);
System.out.println("Student Name :: "+student.getName());
System.out.println("Student Roll :: "+student.getStudentId());
System.out.println("Student Marks :: "+student.getMarks());
}
}
Even if you are getting below exceptions, just you follow the above steps and add proper version of jar file, all your below exception be removed.
Exception in thread "main" java.lang.NoSuchMethodError: org.slf4j.Logger.isTraceEnabled()Z
Exception in thread "main" java.lang.IllegalAccessError: tried to access field org.hibernate.cfg.Configuration.xmlHelper from class org.hibernate.cfg.AnnotationConfiguration
Exception in thread "main" java.lang.NoSuchFieldError: sqlResultSetMappings
That's it ........... :)
Thanks ..... :)
Saturday, June 5, 2010
How to install Eclipse on Linux. Eclipse Galileo on Linux
java should be installed before install the Eclipse. Just check
java -version
Follow these steps to install Eclipse Galileo on linux.
1. Download Eclipse for Linux from here.
Choose Eclipse IDE for Java EE Developers (190 MB) Linux 32 bit. You will get eclipse-jee-galileo-SR2-linux-gtk.tar.gz is being save.
2. Save this file in your favorite location. In my case /home/binod
3. Run this below command
[root@localhost binod]# tar -xzvf eclipse-jee-galileo-SR2-linux-gtk.tar.gz
It will create directory eclipse in /home/binod
4. cd eclipse
[root@localhost binod]# cd eclipse
5. and start eclipse
./eclipse
If everything fine then you will get eclipse window and you can start the work
If you are getting below error:
Warning: -XX:MaxPermSize=256m not understood. Ignoring.
Warning: -Xms40m not understood. Ignoring.
Warning: -Xmx512m not understood. Ignoring.
Warning: -jar not understood. Ignoring.
Exception in thread "main" java.lang.NoClassDefFoundError:
.home.binod.eclipse.plugins.org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
at gnu.gcj.runtime.FirstThread.run() (/usr/lib/libgcj.so.5.0.0)
at _Jv_ThreadRun(java.lang.Thread) (/usr/lib/libgcj.so.5.0.0)
at _Jv_RunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/libgcj.so.5.0.0)
at __gcj_personality_v0 (/home/binod/eclipse/java.version=1.4.2)
at __libc_start_main (/lib/tls/libc-2.3.4.so)
at _Jv_RegisterClasses (/home/binod/eclipse/java.version=1.4.2)
SOLUTION here:
check your JAVA_HOME using this below command
[root@localhost eclipse]# echo $JAVA_HOME
If you do not get result means your path does not set.
Then use this command to set JAVA_HOME path
[root@localhost eclipse]# export PATH=$PATH:/usr/java/jdk1.6.0_20/bin/
[root@localhost eclipse]# export JAVA_HOME=/usr/java/jdk1.6.0_20
In my case Java has been installed at /usr/java/jdk1.6.0_20
Now run this command to verify whether your path and JAVA_HOME is set proplery
echo $PATH
echo $JAVA_HOME
Now you can open eclipse using this below command
[root@localhost eclipse]# ./eclipse -vm /usr/java/jre1.6.0_20/bin
That's it .......... :)
Thanks ...... :)
Friday, June 4, 2010
Best waty to thread implementation in Java, Threads pools with the Executor Framework
Threads were the first approach in Java to support concurrency. The usage of the threads has the following disadvantages.
1. Creating a new thread causes some performance overhead
2. Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.
3.You cannot easily control the number of threads, therefore you may run into out of memory errors due to too many threads.
The java.util.concurrent package offers improved support for concurrency compared to threads. The java.util.concurrent package helps solving several of the isues with threads.
Threads pools with the Executor Framework
Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed. A thread pool can be described as a collection of runnables (work queue) and a connections of running threads. These threads are constantly running and are checking the work query for new work. If there is new work to be done they execute this Runnable. The Thread class itself provides a method, e.g. execute (Runnable r) to add runnables to the work queue.
The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.
If you want to use one thread pool with one thread which executes several runnables you can use Executors.newSingleThreadExecutor();
Create two java files:
MyRunnable.java
package com.suman;
/**
* @author Binod Suman
*/
public class MyRunnable implements Runnable {
private final String sql;
MyRunnable(String sql) {this.sql = sql;}
@Override
public void run() {
long sum = 0;
for (long i = 1; i < 5; i++) {
System.out.println(sql);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
App.java
package com.suman;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class App
{
private static final int noOfThreadInPool = 10;
public static void main( String[] args )
{
ExecutorService executor = Executors.newFixedThreadPool(noOfThreadInPool);
String sql="sql";
List> list = new ArrayList>();
for (int i = 1; i <=5; i++) {
if(i==1)sql="FIRST";
if(i==2)sql="SECOND";
if(i==3)sql="THIRD";
if(i==4)sql="FOURTH";
if(i==5)sql="FIFTH";
Runnable worker = new MyRunnable(sql);
executor.execute(worker);
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown(); // Very Important
// Wait until all threads are finish
while (!executor.isTerminated()) {}
System.out.println("Finished all threads");
}
}
The main benefit of Executors Framework that you no need to manage thread yourself. Here you can give how many thread maximum do you want to generate in threadpool.
private static final int noOfThreadInPool= 10;
ExecutorService executor = Executors.newFixedThreadPoolnoOfThreadInPool
If you give noOfThreadInPool=5 then it will only create 5 thread to threadpool and you request for 6th thread to call executor.execute(worker); then it has to finish until one thread will free.
How you will use this in your project.
Suppose if you have one fixed work that you have to execute 10 times then make that method inside the MyRunnbale.java and put that method in run() method and call
Runnable worker = new MyRunnable(sql);
executor.execute(worker);
10 times.
But you can not return any value from MyRunnable class as run() method return type is void.
In case you expect your threads to return a computed result you can use java.util.concurrent.Callable. Callables allow to return values after competition. Callable uses generic to define the type of object which is returned.
If you submit a callable to an executor the framework returns a java.util.concurrent.Future. This futures can be used to check the status of a callable and to retrieve the result from the callable.
On the executor you can use the method submit to submit a Callable and to get a future. To retrieve the result of the future use the get() method.
Future and Collable Example
Create one more java file
MyCallable.java
package com.suman;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
/**
* @author Binod Suman
*/
public class MyCallable implements Callable
1. Creating a new thread causes some performance overhead
2. Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.
3.You cannot easily control the number of threads, therefore you may run into out of memory errors due to too many threads.
The java.util.concurrent package offers improved support for concurrency compared to threads. The java.util.concurrent package helps solving several of the isues with threads.
Threads pools with the Executor Framework
Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed. A thread pool can be described as a collection of runnables (work queue) and a connections of running threads. These threads are constantly running and are checking the work query for new work. If there is new work to be done they execute this Runnable. The Thread class itself provides a method, e.g. execute (Runnable r) to add runnables to the work queue.
The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds lifecycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.
If you want to use one thread pool with one thread which executes several runnables you can use Executors.newSingleThreadExecutor();
Create two java files:
MyRunnable.java
package com.suman;
/**
* @author Binod Suman
*/
public class MyRunnable implements Runnable {
private final String sql;
MyRunnable(String sql) {this.sql = sql;}
@Override
public void run() {
long sum = 0;
for (long i = 1; i < 5; i++) {
System.out.println(sql);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
App.java
package com.suman;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class App
{
private static final int noOfThreadInPool = 10;
public static void main( String[] args )
{
ExecutorService executor = Executors.newFixedThreadPool(noOfThreadInPool);
String sql="sql";
List
for (int i = 1; i <=5; i++) {
if(i==1)sql="FIRST";
if(i==2)sql="SECOND";
if(i==3)sql="THIRD";
if(i==4)sql="FOURTH";
if(i==5)sql="FIFTH";
Runnable worker = new MyRunnable(sql);
executor.execute(worker);
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown(); // Very Important
// Wait until all threads are finish
while (!executor.isTerminated()) {}
System.out.println("Finished all threads");
}
}
The main benefit of Executors Framework that you no need to manage thread yourself. Here you can give how many thread maximum do you want to generate in threadpool.
private static final int noOfThreadInPool= 10;
ExecutorService executor = Executors.newFixedThreadPoolnoOfThreadInPool
If you give noOfThreadInPool=5 then it will only create 5 thread to threadpool and you request for 6th thread to call executor.execute(worker); then it has to finish until one thread will free.
How you will use this in your project.
Suppose if you have one fixed work that you have to execute 10 times then make that method inside the MyRunnbale.java and put that method in run() method and call
Runnable worker = new MyRunnable(sql);
executor.execute(worker);
10 times.
But you can not return any value from MyRunnable class as run() method return type is void.
In case you expect your threads to return a computed result you can use java.util.concurrent.Callable. Callables allow to return values after competition. Callable uses generic to define the type of object which is returned.
If you submit a callable to an executor the framework returns a java.util.concurrent.Future. This futures can be used to check the status of a callable and to retrieve the result from the callable.
On the executor you can use the method submit to submit a Callable and to get a future. To retrieve the result of the future use the get() method.
Future and Collable Example
Create one more java file
MyCallable.java
package com.suman;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
/**
* @author Binod Suman
*/
public class MyCallable implements Callable
- {
private final String sql;
MyCallable(String sql) {this.sql = sql;}
@Override
public List call() throws Exception {
long sum = 0;
List
for (long i = 1; i < 6; i++) {
System.out.println(sql);
list.add(sql+i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return list;
}
}
And do some change in App.java
package com.suman;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class App
{
private static final int noOfThreadInThreadPool = 10;
public static void main( String[] args )
{
ExecutorService executor = Executors.newFixedThreadPool(noOfThreadInThreadPool);
String sql="sql";
List
for (int i = 1; i <=5; i++) {
if(i==1)sql="FIRST";
if(i==2)sql="SECOND";
if(i==3)sql="THIRD";
if(i==4)sql="FOURTH";
if(i==5)sql="FIFTH";
// Runnable worker = new MyRunnable(sql);
// executor.execute(worker);
Callable
- worker = new MyCallable(sql);
Future
- submit = executor.submit(worker);
list.add(submit);
}
// To see the result
for (Future
- future : list) {
try {
List list2 = future.get();
System.out.println("ALL LIST:: "+list2);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {}
System.out.println("Finished all threads");
}
}
I think, it is best way to use the thread. Your suggestions or question is always most welcom. :)
Thanks ........... :)
source: http://www.vogella.de/articles/JavaConcurrency/article.html#threadpools
JPA One to Many and Many to One easy example
Please follow two previous posting on JPA for basic start
1. JPA getting started, easy example of JPA, JPA annotation example, JPA with Hibernate
2. Configure JPA during run time, dynamic JPA Configuration using Spring context
Now OnetoMany and ManytoOne Example.
Suppose company has many employee. So during saving of company we can save employee also and during fetching company record we can fetch employee records also.
Create one Employee.java
package com.suman;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author Binod Suman
*/
@Entity
@Table(name="blogemployee")
public class Employee {
@Id
private int id;
@Column(name="cid")
private int companyId;
private String name;
private String designation;
@ManyToOne
@JoinColumn(name="cid",nullable=false, insertable=false, updatable=false)
private Company company;
// cid column should be there in company table.
public Employee() { }
public Employee(int companyId, String name, String designation) {
super();
this.companyId = companyId;
this.name = name;
this.designation = designation;
}
public Employee(int id, int companyId, String name, String designation) {
super();
this.id = id;
this.companyId = companyId;
this.name = name;
this.designation = designation;
}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public int getCompanyId() {return companyId;}
public void setCompanyId(int companyId) {this.companyId = companyId;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getDesignation() {return designation;}
public void setDesignation(String designation) {this.designation = designation;}
public Company getCompany() {return company;}
public void setCompany(Company company) {this.company = company;}
}
Company.java
package com.suman;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.OptimisticLock;
/**
* @author Binod Suman
*/
@Entity
@Table(name="blogcompany")
public class Company {
@Id
private int id;
@Column(name="cname")
private String name;
private String city;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
private List employees;
@Transient
Logger log = Logger.getLogger(Company.class);
// Use Transient if you dont want to mapping your java bean to database table column.
public Company(){};
public Company(String name, String city) {
super();
this.name = name;
this.city = city;
}
public Company(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getCity() {return city;}
public void setCity(String city) {this.city = city;}
public List getEmployees() {return employees;}
public void setEmployees(List employees) {this.employees = employees;}
}
TestApplication.java
package com.suman;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
// test.fetchCompanyData();
// test.saveCompanyAndEmployee();
test.fetchCompanyAndEmployee();
}
public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
properties.put("hibernate.format_sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
public void saveCompanyAndEmployee(){
log.info("Company and Employee data are going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(145,"TecnoTree","Finland");
List employees = new ArrayList();
Employee employee = new Employee(10,145,"Binod","Project Manager");
// entityManager.persist(employee);
employees.add(employee);
employee = new Employee(11,145,"Binod Suman","Team Leader");
employees.add(employee);
company.setEmployees(employees);
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company and Employee data have been saved");
}
public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List list = (List) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}
public void fetchCompanyAndEmployee(){
Query query = em.createQuery("SELECT c FROM Company c");
List list = (List) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("Company Id :: "+company.getId());
List employees = company.getEmployees();
log.info("Employees.size() :: "+employees.size());
for(Employee employee : employees){
log.info("Employee Name :: "+employee.getName());
log.info("Employee Designation :: "+employee.getDesignation());
}
log.info("***************************");
}
}
}
Some time if you have father -> child -> child mapping then it doest not work properly then use this below mapping in father and his child java bean.
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
@LazyCollection(LazyCollectionOption.FALSE)
private List employees;
If you have question and doubt then please give your comment or if you have any feedback.
Thanks .......... :)
1. JPA getting started, easy example of JPA, JPA annotation example, JPA with Hibernate
2. Configure JPA during run time, dynamic JPA Configuration using Spring context
Now OnetoMany and ManytoOne Example.
Suppose company has many employee. So during saving of company we can save employee also and during fetching company record we can fetch employee records also.
Create one Employee.java
package com.suman;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author Binod Suman
*/
@Entity
@Table(name="blogemployee")
public class Employee {
@Id
private int id;
@Column(name="cid")
private int companyId;
private String name;
private String designation;
@ManyToOne
@JoinColumn(name="cid",nullable=false, insertable=false, updatable=false)
private Company company;
// cid column should be there in company table.
public Employee() { }
public Employee(int companyId, String name, String designation) {
super();
this.companyId = companyId;
this.name = name;
this.designation = designation;
}
public Employee(int id, int companyId, String name, String designation) {
super();
this.id = id;
this.companyId = companyId;
this.name = name;
this.designation = designation;
}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public int getCompanyId() {return companyId;}
public void setCompanyId(int companyId) {this.companyId = companyId;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getDesignation() {return designation;}
public void setDesignation(String designation) {this.designation = designation;}
public Company getCompany() {return company;}
public void setCompany(Company company) {this.company = company;}
}
Company.java
package com.suman;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.OptimisticLock;
/**
* @author Binod Suman
*/
@Entity
@Table(name="blogcompany")
public class Company {
@Id
private int id;
@Column(name="cname")
private String name;
private String city;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
private List
@Transient
Logger log = Logger.getLogger(Company.class);
// Use Transient if you dont want to mapping your java bean to database table column.
public Company(){};
public Company(String name, String city) {
super();
this.name = name;
this.city = city;
}
public Company(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getCity() {return city;}
public void setCity(String city) {this.city = city;}
public List
public void setEmployees(List
}
TestApplication.java
package com.suman;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
// test.fetchCompanyData();
// test.saveCompanyAndEmployee();
test.fetchCompanyAndEmployee();
}
public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
properties.put("hibernate.format_sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
public void saveCompanyAndEmployee(){
log.info("Company and Employee data are going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(145,"TecnoTree","Finland");
List
Employee employee = new Employee(10,145,"Binod","Project Manager");
// entityManager.persist(employee);
employees.add(employee);
employee = new Employee(11,145,"Binod Suman","Team Leader");
employees.add(employee);
company.setEmployees(employees);
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company and Employee data have been saved");
}
public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}
public void fetchCompanyAndEmployee(){
Query query = em.createQuery("SELECT c FROM Company c");
List
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("Company Id :: "+company.getId());
List
log.info("Employees.size() :: "+employees.size());
for(Employee employee : employees){
log.info("Employee Name :: "+employee.getName());
log.info("Employee Designation :: "+employee.getDesignation());
}
log.info("***************************");
}
}
}
Some time if you have father -> child -> child mapping then it doest not work properly then use this below mapping in father and his child java bean.
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "company")
@LazyCollection(LazyCollectionOption.FALSE)
private List
If you have question and doubt then please give your comment or if you have any feedback.
Thanks .......... :)
Thursday, June 3, 2010
Configure JPA during run time, dynamic JPA Configuration using Spring context
You can set the database information during run time. Then remove all the database specific stuff
from persistance.xml and use Hash properties in your java class.
1. Removed all your database properties from persistance.xml
<persistence>
<persistence-unit name="jpablogPUnit" transaction-type="RESOURCE_LOCAL">
<class>com.suman.Company</class>
</persistence-unit>
</persistence>
2. Changed your java file where you are configuring entityManager, in our case TestApplication.java
package com.suman;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.saveCompany();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManagerFactory emf;
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
}
Now run the application.
One more record has been inserted.
How to fetch data using JPA
Change the code of TestApplcation.java
package com.suman;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
test.fetchCompanyData();
}
public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List<Company> list = (List<Company>) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}
}
You can configure the EntityManagerFactory from spring configuration file also.
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
lazy-init="false">
<property name="persistenceUnitName" value="VMSPersistenceUnit" />
<property name="dataSource" ref="sourceDataSource" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
If you want to configure entityManagerFactory during runt time then use these code. As if you dont have database name and information then you can not use the spring context for entityManagerFactory.
private EntityManagerFactory entityManagerFactory;
private JpaTemplate jpaTemplate;
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(sourceDataSource);
bean.afterPropertiesSet();
entityManagerFactory = bean.getObject();
log.info("entityManagerFactory :: " + entityManagerFactory);
this.jpaTemplate = new JpaTemplate(this.entityManagerFactory);
Even you can fetch record in batch wise manner also.
Use this below code:
public Collection fetchQueryListFromSourceDatabaseForSubscriber(final String sql,final int firstPosition, final int numberOfRecords) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();
return result;
}
});
}
If will fetch record from firstPosition and number of record will be numberOfRecords.
A persistence provider may or may not optimize access to database using database specific limit clause, like select * from table limit 10,
Then in TestApplication.java
public Collection fetchQueryListFromSourceDatabase(final String sql) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
List result = query.getResultList();
log.info("FINALLY JPA WORKING :: "+result.size());
return result;
}
});
}
Please feedback to improve this tutorial ....... :)
Thanks :)
from persistance.xml and use Hash properties in your java class.
1. Removed all your database properties from persistance.xml
<persistence>
<persistence-unit name="jpablogPUnit" transaction-type="RESOURCE_LOCAL">
<class>com.suman.Company</class>
</persistence-unit>
</persistence>
2. Changed your java file where you are configuring entityManager, in our case TestApplication.java
package com.suman;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.saveCompany();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManagerFactory emf;
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
}
Now run the application.
One more record has been inserted.
How to fetch data using JPA
Change the code of TestApplcation.java
package com.suman;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
test.fetchCompanyData();
}
public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List<Company> list = (List<Company>) query.getResultList();
log.info(list);
for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}
}
You can configure the EntityManagerFactory from spring configuration file also.
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
lazy-init="false">
<property name="persistenceUnitName" value="VMSPersistenceUnit" />
<property name="dataSource" ref="sourceDataSource" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
If you want to configure entityManagerFactory during runt time then use these code. As if you dont have database name and information then you can not use the spring context for entityManagerFactory.
private EntityManagerFactory entityManagerFactory;
private JpaTemplate jpaTemplate;
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(sourceDataSource);
bean.afterPropertiesSet();
entityManagerFactory = bean.getObject();
log.info("entityManagerFactory :: " + entityManagerFactory);
this.jpaTemplate = new JpaTemplate(this.entityManagerFactory);
Even you can fetch record in batch wise manner also.
Use this below code:
public Collection fetchQueryListFromSourceDatabaseForSubscriber(final String sql,final int firstPosition, final int numberOfRecords) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();
return result;
}
});
}
If will fetch record from firstPosition and number of record will be numberOfRecords.
A persistence provider may or may not optimize access to database using database specific limit clause, like select * from table limit 10,
Then in TestApplication.java
public Collection fetchQueryListFromSourceDatabase(final String sql) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
List result = query.getResultList();
log.info("FINALLY JPA WORKING :: "+result.size());
return result;
}
});
}
Please feedback to improve this tutorial ....... :)
Thanks :)
Saturday, May 22, 2010
JPA getting started, easy example of JPA, JPA annotation example, JPA with Hibernate
Very basic example of how to implement JPA using hibernate provider for mysql database.
Create one project in Eclipse (say JPABlogTestHibernate) add these jar files.
1. log4j-1.2.15.jar
2. mysql-connector-java-3.1.12-bin.jar
3. persistence-api-1.0.jar
4. slf4j-simple-1.4.2.jar
5. cglib-2.1_3.jar
6. cglib-asm-1.0.jar
7. commons-collections-3.2.jar
8. commons-logging-1.1.jar
9. hibernate-core-3.3.1.GA.jar
10. hibernate-entitymanager-3.3.1.ga.jar
11. javassist-3.3.jar
12. jta-1.0.1B.jar
13. jboss-archive-browsing-5.0.0alpha-200607201-119.jar
14. dom4j-1.6.1.jar
15. slf4j-api-1.4.2.jar
16. hibernate-tools-3.2.0.beta9a.jar
17. hibernate-annotations-3.4.0.GA.jar
18. hibernate-commons-annotations-3.1.0.GA.jar
19. antlr-2.7.7.jar
Create one persistence.xml inside src\META-INF folder.
create one package inside src say com.suman
Add these files
Company.java
TestApplication.java
persistence.xml
log4j.xml inside src folder
Company.java (src\com\suman)
package com.suman;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
@Entity
@Table(name="blogcompany")
public class Company {
@Id
private int id;
@Column(name="cname")
private String name;
private String city;
@Transient
Logger log = Logger.getLogger(Company.class);
public Company(){};
public Company(String name, String city) {
super();
this.name = name;
this.city = city;
}
public Company(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
TestApplication.java (src\com\suman)
package com.suman;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.saveCompany();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("jpablogPUnit");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(110,"TecnoTree","Bangalore");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
}
Create database table blogcompany inside the sumandb database.
CREATE TABLE blogcompany (
id int(11) NOT NULL,
cname varchar(100) default NULL,
city varchar(100) default NULL,
PRIMARY KEY (id)
)
Now you can run the TestApplication.java and see the log on console
One record has been inserted into blogcompany table.
That's easy ............ :)
If you have question and doubt then please give your comment or if you have any feedback.
Thanks .......... :)
Create one project in Eclipse (say JPABlogTestHibernate) add these jar files.
1. log4j-1.2.15.jar
2. mysql-connector-java-3.1.12-bin.jar
3. persistence-api-1.0.jar
4. slf4j-simple-1.4.2.jar
5. cglib-2.1_3.jar
6. cglib-asm-1.0.jar
7. commons-collections-3.2.jar
8. commons-logging-1.1.jar
9. hibernate-core-3.3.1.GA.jar
10. hibernate-entitymanager-3.3.1.ga.jar
11. javassist-3.3.jar
12. jta-1.0.1B.jar
13. jboss-archive-browsing-5.0.0alpha-200607201-119.jar
14. dom4j-1.6.1.jar
15. slf4j-api-1.4.2.jar
16. hibernate-tools-3.2.0.beta9a.jar
17. hibernate-annotations-3.4.0.GA.jar
18. hibernate-commons-annotations-3.1.0.GA.jar
19. antlr-2.7.7.jar
Create one persistence.xml inside src\META-INF folder.
create one package inside src say com.suman
Add these files
Company.java
TestApplication.java
persistence.xml
log4j.xml inside src folder
Company.java (src\com\suman)
package com.suman;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
@Entity
@Table(name="blogcompany")
public class Company {
@Id
private int id;
@Column(name="cname")
private String name;
private String city;
@Transient
Logger log = Logger.getLogger(Company.class);
public Company(){};
public Company(String name, String city) {
super();
this.name = name;
this.city = city;
}
public Company(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
TestApplication.java (src\com\suman)
package com.suman;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;
/**
* @author Binod Suman
*/
public class TestApplication {
Logger log = Logger.getLogger(TestApplication.class);
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.saveCompany();
}
public void saveCompany(){
log.info("Company data is going to save");
EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("jpablogPUnit");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(110,"TecnoTree","Bangalore");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}
}
Create database table blogcompany inside the sumandb database.
CREATE TABLE blogcompany (
id int(11) NOT NULL,
cname varchar(100) default NULL,
city varchar(100) default NULL,
PRIMARY KEY (id)
)
Now you can run the TestApplication.java and see the log on console
One record has been inserted into blogcompany table.
That's easy ............ :)
If you have question and doubt then please give your comment or if you have any feedback.
Thanks .......... :)
Saturday, May 15, 2010
Spring Transaction using JDBCTemplate, Spring Transaction easy example
Here I am going to show very easy example of Spring jdbcTemplate transaction. First I will write one small example to save data into mysql database without handling any transaction then we will solve problem with use of Spring transation.
Create one project (JDBCTemplateTransaction) in eclipse and add these below mentioned external jar:
1. spring-2.5.6.jar
2. mysql-connector-java-5.1.9.jar
3. log4j-1.2.15.jar
4. commons-logging-1.0.4.jar
5. commons-dbcp-1.2.2.jar
6. commons-pool-1.3.jar
Create one package in src folder say com.suman and add these java files.
1. App.java
2. IDaoOperation.java (Interface)
3. DaoOperation.java
All the code are below.
Create three file inside the src folder
1. project-config.properties
2. project-config.xml
3. log4j.xml
******** code section ************
App.java
package com.suman;
import org.apache.log4j.Logger;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
Logger log = Logger.getLogger(App.class);
IDaoOperation daoOperation;
log.info( "Check Spring Transaction using jdbcTemplate" );
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("project-config.xml");
daoOperation = (IDaoOperation) context.getBean("daoOperation");
daoOperation.saveStudent();
log.info("THIS IS MAIN METHOD OF SPRING TEST");
}
}
IDaoOperation.java
package com.suman;
/**
* @author Binod Suman
*/
public interface IDaoOperation {
public void saveStudent();
}
DaoOperation.java
package com.suman;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcOperations;
/**
* @author Binod Suman
*/
public class DaoOperation implements IDaoOperation{
private DataSource dataSource;
private Logger log;
private JdbcOperations jdbc;
public void saveStudent(){
String sql = "insert into student (id,name,roll) values (1,'Binod',110)";
executeSQL(sql);
saveHostel();
}
public void saveHostel(){
String sql = "insert into hostel (id,name,roll) values (1,'Yamuna',1)";
executeSQL(sql);
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public JdbcOperations getJdbc() {
return jdbc;
}
public void setJdbc(JdbcOperations jdbc) {
this.jdbc = jdbc;
}
public void init(){
log = Logger.getLogger(DaoOperation.class);
setDatabase();
}
public void executeSQL(String sql) {
try{
log.debug("exec SQL: " + sql);
jdbc.execute(sql);
}catch(Exception e){
log.error("some problem during executing sql");
}
}
public void executeSQL(Collection<String> sqlList) throws IOException,
SQLException {
for (String sql : sqlList) {
executeSQL(sql);
}
}
public void setDatabase(){
executeSQL("USE sumandb");
}
}
project-config.properties
db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost
db.username = root
db.password = mysql
project-config.xml
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:mbean-server/>
<context:property-placeholder location="classpath:/project-config.properties" />
<bean id="daoOperation"
class="com.suman.DaoOperation"
init-method="init" p:dataSource-ref="dataSource"
p:jdbc-ref="jdbc" />
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
<!--Infrastructure setup -->
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- logs to system console -->
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<param name="Threshold" value="ALL" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n" />
</layout>
</appender>
<logger name="org.springframework" additivity="false">
<level value="WARN" />
<appender-ref ref="CONSOLE"/>
</logger>
<root>
<level value="ALL" />
<appender-ref ref="CONSOLE" />
</root>
</log4j:configuration>
Create database with name sumandb in mysql in localhost at 3306 port.
Then create the two table
create table
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(90) default NULL,
`roll` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
create table
CREATE TABLE `hostel` (
`id` int(11) NOT NULL,
`name` varchar(200) default NULL,
`roll` int(11) default NULL,
PRIMARY KEY (`id`),
KEY `FK_hostel` (`roll`),
CONSTRAINT `FK_hostel` FOREIGN KEY (`roll`) REFERENCES `student` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
RUN THE APPLICATION :
Now run App.java
you will see one record has been inserted into student table and one record into hostel table.
Here student.id is the foreign key for hostel.roll. So without having id (say x) exist in student table you can not save any record into hostel table with roll x.
** IMP **. But I am going to save into both table. I will give id 2 in student table and roll 9 in hostel table.
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
String sql = "insert into hostel (id,name,roll) values (1,'Yamuna',9)";
See what is going to happen.
One recrod has been inserted in student table but no new record into hostel table. BUT in student table record should not have been inserted if we will use TRANSACTION.
delete that recrod from student table.
DELETE FROM student WHERE id = 2
NOW I AM GOING TO IMPLEMENT SPRING TRANSACTION.
FIRST WAY TO IMPLEMENT SPRING TRANSACTION.
Change saveStudetn() of DaoOperation.java method and change import:
public void saveStudent(){
TransactionTemplate tt = new TransactionTemplate();
tt.setTransactionManager(new DataSourceTransactionManager(getDataSource()));
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
executeSQL(sql);
saveHostel();
}
});
}
Change import
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
Now you run App.java, there will NOT be any record will get inserted either in Student or hostel table. Transaction has rolled back all the database opeartion if any operation gets fail.
Now change sql:
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
String sql = "insert into hostel (id,name,roll) values (2,'Yamuna',2)";
Now run the application.
Both record have been saved successfully.
SECON WAY TO IMPLEMENT SPRING TRANSACTION.
Change saveStudetn() of DaoOperation.java method and change import:
@Transactional (propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void saveStudent(){
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
executeSQL(sql);
saveHostel();
}
Change sql to check whether transaction is working correctly:
String sql = "insert into student (id,name,roll) values (3,'Ayush',120)";
String sql = "insert into hostel (id,name,roll) values (3,'Ganga',9)";
no any record should be inserterd.
Now change sql, and both record should be inserted.
String sql = "insert into student (id,name,roll) values (3,'Ayush',120)";
String sql = "insert into hostel (id,name,roll) values (3,'Ganga',3)";
Thats easy ............... :)
Now I checked with huge data. If any record will not be able to insert then all the previouse record will rolled back.
Changed both method of DaoOpeartion.java
public void saveStudent(){
for(int i=0;i<10;i++){
String sqlStudetn = "insert into student (id,name,roll) values ("+i+",'Ayush',120)";
String sqlHostel = "insert into hostel (id,name,roll) values ("+i+",'Ganga',"+i+")";
executeSQL(sqlStudetn);
saveHostel(sqlHostel);
}
}
public void saveHostel(String sql){
executeSQL(sql);
}
Run the App.java
10 record should be inserted into Student table and 10 records should be inserted into hostel table.
Now add last recrod that should not be insert to avoid foreign key constraints. Then all the previous 10 record will be rolled back;
DELETE FROM hostel;
DELETE FROM student;
@Transactional (propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void saveStudent(){
for(int i=0;i<10;i++){
String sqlStudetn = "insert into student (id,name,roll) values ("+i+",'Ayush',120)";
String sqlHostel = "insert into hostel (id,name,roll) values ("+i+",'Ganga',"+i+")";
executeSQL(sqlStudetn);
saveHostel(sqlHostel);
}
String sqlHostel = "insert into hostel (id,name,roll) values (10,'Ganga',10)";
saveHostel(sqlHostel);
}
Now run the App.java
and check database, there is no any record has been inserted either in student table or Hostel table.
That's easy .............. :)
Create one project (JDBCTemplateTransaction) in eclipse and add these below mentioned external jar:
1. spring-2.5.6.jar
2. mysql-connector-java-5.1.9.jar
3. log4j-1.2.15.jar
4. commons-logging-1.0.4.jar
5. commons-dbcp-1.2.2.jar
6. commons-pool-1.3.jar
Create one package in src folder say com.suman and add these java files.
1. App.java
2. IDaoOperation.java (Interface)
3. DaoOperation.java
All the code are below.
Create three file inside the src folder
1. project-config.properties
2. project-config.xml
3. log4j.xml
******** code section ************
App.java
package com.suman;
import org.apache.log4j.Logger;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
Logger log = Logger.getLogger(App.class);
IDaoOperation daoOperation;
log.info( "Check Spring Transaction using jdbcTemplate" );
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("project-config.xml");
daoOperation = (IDaoOperation) context.getBean("daoOperation");
daoOperation.saveStudent();
log.info("THIS IS MAIN METHOD OF SPRING TEST");
}
}
IDaoOperation.java
package com.suman;
/**
* @author Binod Suman
*/
public interface IDaoOperation {
public void saveStudent();
}
DaoOperation.java
package com.suman;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcOperations;
/**
* @author Binod Suman
*/
public class DaoOperation implements IDaoOperation{
private DataSource dataSource;
private Logger log;
private JdbcOperations jdbc;
public void saveStudent(){
String sql = "insert into student (id,name,roll) values (1,'Binod',110)";
executeSQL(sql);
saveHostel();
}
public void saveHostel(){
String sql = "insert into hostel (id,name,roll) values (1,'Yamuna',1)";
executeSQL(sql);
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public JdbcOperations getJdbc() {
return jdbc;
}
public void setJdbc(JdbcOperations jdbc) {
this.jdbc = jdbc;
}
public void init(){
log = Logger.getLogger(DaoOperation.class);
setDatabase();
}
public void executeSQL(String sql) {
try{
log.debug("exec SQL: " + sql);
jdbc.execute(sql);
}catch(Exception e){
log.error("some problem during executing sql");
}
}
public void executeSQL(Collection<String> sqlList) throws IOException,
SQLException {
for (String sql : sqlList) {
executeSQL(sql);
}
}
public void setDatabase(){
executeSQL("USE sumandb");
}
}
project-config.properties
db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost
db.username = root
db.password = mysql
project-config.xml
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:mbean-server/>
<context:property-placeholder location="classpath:/project-config.properties" />
<bean id="daoOperation"
class="com.suman.DaoOperation"
init-method="init" p:dataSource-ref="dataSource"
p:jdbc-ref="jdbc" />
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
<!--Infrastructure setup -->
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${db.driver}"
p:url="${db.url}" p:username="${db.username}" p:password="${db.password}" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- logs to system console -->
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<param name="Threshold" value="ALL" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n" />
</layout>
</appender>
<logger name="org.springframework" additivity="false">
<level value="WARN" />
<appender-ref ref="CONSOLE"/>
</logger>
<root>
<level value="ALL" />
<appender-ref ref="CONSOLE" />
</root>
</log4j:configuration>
Create database with name sumandb in mysql in localhost at 3306 port.
Then create the two table
create table
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(90) default NULL,
`roll` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
create table
CREATE TABLE `hostel` (
`id` int(11) NOT NULL,
`name` varchar(200) default NULL,
`roll` int(11) default NULL,
PRIMARY KEY (`id`),
KEY `FK_hostel` (`roll`),
CONSTRAINT `FK_hostel` FOREIGN KEY (`roll`) REFERENCES `student` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
RUN THE APPLICATION :
Now run App.java
you will see one record has been inserted into student table and one record into hostel table.
Here student.id is the foreign key for hostel.roll. So without having id (say x) exist in student table you can not save any record into hostel table with roll x.
** IMP **. But I am going to save into both table. I will give id 2 in student table and roll 9 in hostel table.
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
String sql = "insert into hostel (id,name,roll) values (1,'Yamuna',9)";
See what is going to happen.
One recrod has been inserted in student table but no new record into hostel table. BUT in student table record should not have been inserted if we will use TRANSACTION.
delete that recrod from student table.
DELETE FROM student WHERE id = 2
NOW I AM GOING TO IMPLEMENT SPRING TRANSACTION.
FIRST WAY TO IMPLEMENT SPRING TRANSACTION.
Change saveStudetn() of DaoOperation.java method and change import:
public void saveStudent(){
TransactionTemplate tt = new TransactionTemplate();
tt.setTransactionManager(new DataSourceTransactionManager(getDataSource()));
tt.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
executeSQL(sql);
saveHostel();
}
});
}
Change import
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
Now you run App.java, there will NOT be any record will get inserted either in Student or hostel table. Transaction has rolled back all the database opeartion if any operation gets fail.
Now change sql:
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
String sql = "insert into hostel (id,name,roll) values (2,'Yamuna',2)";
Now run the application.
Both record have been saved successfully.
SECON WAY TO IMPLEMENT SPRING TRANSACTION.
Change saveStudetn() of DaoOperation.java method and change import:
@Transactional (propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void saveStudent(){
String sql = "insert into student (id,name,roll) values (2,'Pramod',110)";
executeSQL(sql);
saveHostel();
}
Change sql to check whether transaction is working correctly:
String sql = "insert into student (id,name,roll) values (3,'Ayush',120)";
String sql = "insert into hostel (id,name,roll) values (3,'Ganga',9)";
no any record should be inserterd.
Now change sql, and both record should be inserted.
String sql = "insert into student (id,name,roll) values (3,'Ayush',120)";
String sql = "insert into hostel (id,name,roll) values (3,'Ganga',3)";
Thats easy ............... :)
Now I checked with huge data. If any record will not be able to insert then all the previouse record will rolled back.
Changed both method of DaoOpeartion.java
public void saveStudent(){
for(int i=0;i<10;i++){
String sqlStudetn = "insert into student (id,name,roll) values ("+i+",'Ayush',120)";
String sqlHostel = "insert into hostel (id,name,roll) values ("+i+",'Ganga',"+i+")";
executeSQL(sqlStudetn);
saveHostel(sqlHostel);
}
}
public void saveHostel(String sql){
executeSQL(sql);
}
Run the App.java
10 record should be inserted into Student table and 10 records should be inserted into hostel table.
Now add last recrod that should not be insert to avoid foreign key constraints. Then all the previous 10 record will be rolled back;
DELETE FROM hostel;
DELETE FROM student;
@Transactional (propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void saveStudent(){
for(int i=0;i<10;i++){
String sqlStudetn = "insert into student (id,name,roll) values ("+i+",'Ayush',120)";
String sqlHostel = "insert into hostel (id,name,roll) values ("+i+",'Ganga',"+i+")";
executeSQL(sqlStudetn);
saveHostel(sqlHostel);
}
String sqlHostel = "insert into hostel (id,name,roll) values (10,'Ganga',10)";
saveHostel(sqlHostel);
}
Now run the App.java
and check database, there is no any record has been inserted either in student table or Hostel table.
That's easy .............. :)
Sunday, April 11, 2010
Process the command line with CLI in Java, common CLI example
CLI (=Command Line Interface)
How many times have you written a Java application and had had to rewrite a new way of specifying the input parameters to your application? Wouldn't it be nice if there were one single interface to the way you define the input parameters (mandatory vs. numbers vs. Boolean, etc.), parse these parameters (according to a set of rules), interrogate, and decide the path that your application will take? CLI is the answer.
To run this example, needs commons-cli-1.0.jar in the CLASSPATH. YOu can download from here
Refer of this tutorial.
In CLI, each parameter that you want to specify on the command line is an Option. Create an Options object, add individual Option objects to it, then use the CLI-supplied methods to parse the user's input parameters. An Option might require the user to input a value as well; for example, if the name of a file is required. In such a case, the Option must be created where this is explicitly specified.
Create your Options:
Options options = new Options();
options.addOption("n", true, "[name] your name");
2nd way is by creating an Option and then adding it
Option timeOption = new Option("t", false, "current time");
options.addOption(timeOption);
The addOption() method has three parameters.
1. The first parameter is a java.lang.String that represents the option (That would be given by user with - like -t or -n during execution of code).
2. The second parameter is a boolean that specifies whether the option requires an argument or not. For example -n Nik, here I gave Nik with -n because n is defined as true, if I will not give name then it would not be accept. For -t, no need to supply any argument as it is false. Even though if you give any argument, it would not be accept means it would be ignore that extra argument. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so false is passed.
3. The third parameter is the description of the option. This description will be used in the usage text of the application. When you will not give proper argument that time it will show like help command.
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);
The parse methods of CommandLineParser are used to parse the command line arguments. The PosixPaser is great when you need to handle options that are one character long, like the t option in this example. Else use BasicParser for more than one character input.
Now we need to check if the t option is present. To do this we will interrogate the CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise it returns false.
if(cmd.hasOption("t")) {
// print the date and time
}
else {
// print the some thing else;
}
One complete example on CLI :
import org.apache.commons.cli.*;
public class CLIDemo{
public static void main(String args[]){
Options options = new Options();
options.addOption("n", true, "[name] your name");
Option timeOption = new Option("t", false, "current time");
options.addOption(timeOption);
// ** now lets parse the input
CommandLineParser parser = new BasicParser();
CommandLine cmd;
try{
cmd = parser.parse(options, args);
}catch (ParseException pe){ usage(options); return; }
// ** now lets interrogate the options and execute the relevant parts
if(cmd.hasOption("t")){
System.out.println("You have given argument is t");
System.err.println("Date/Time: " + new java.util.Date());
}
if(cmd.hasOption("n")){
System.out.println("You have given argument is n");
System.err.println("Nice to meet you: " + cmd.getOptionValue('n'));
}
}
private static void usage(Options options){
// Use the inbuilt formatter class
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "CLIDemo", options );
}
}
In the above code, there is no any use to use cmd.getOptionValue('t') with t condition, as t has been setup false and it would be never get any extra argument as n.
How to run CLI example:
D:\JavaTest>javac CLIDemo.java
D:\JavaTest>java CLIDemo
D:\JavaTest>java CLIDemo -t
You have given argument is t
Date/Time: Sun Apr 11 21:19:50 EEST 2010
D:\JavaTest>java CLIDemo -n
usage: CLIDemo
-n [name] your name
-t current time
D:\JavaTest>java CLIDemo -n Nik
You have given argument is n
Nice to meet you: Nik
D:\JavaTest>java CLIDemo -n "Nik Suman"
You have given argument is n
Nice to meet you: Nik Suman
D:\JavaTest>
First time I did not give any argument, so there is no any output.
Second time I gave -t as argument then we got output as per our expectation.
Third time I gave -n. This time, durint parsing the input it got error so execute catch part. Actually -n has been setup with true so we have to have some
extra argument with -n. In catch block we are printing the help format.
Forth time I gave -n With some name, so it worked perfectly.
How many times have you written a Java application and had had to rewrite a new way of specifying the input parameters to your application? Wouldn't it be nice if there were one single interface to the way you define the input parameters (mandatory vs. numbers vs. Boolean, etc.), parse these parameters (according to a set of rules), interrogate, and decide the path that your application will take? CLI is the answer.
To run this example, needs commons-cli-1.0.jar in the CLASSPATH. YOu can download from here
Refer of this tutorial.
In CLI, each parameter that you want to specify on the command line is an Option. Create an Options object, add individual Option objects to it, then use the CLI-supplied methods to parse the user's input parameters. An Option might require the user to input a value as well; for example, if the name of a file is required. In such a case, the Option must be created where this is explicitly specified.
Create your Options:
Options options = new Options();
options.addOption("n", true, "[name] your name");
2nd way is by creating an Option and then adding it
Option timeOption = new Option("t", false, "current time");
options.addOption(timeOption);
The addOption() method has three parameters.
1. The first parameter is a java.lang.String that represents the option (That would be given by user with - like -t or -n during execution of code).
2. The second parameter is a boolean that specifies whether the option requires an argument or not. For example -n Nik, here I gave Nik with -n because n is defined as true, if I will not give name then it would not be accept. For -t, no need to supply any argument as it is false. Even though if you give any argument, it would not be accept means it would be ignore that extra argument. In the case of a boolean option (sometimes referred to as a flag) an argument value is not present so false is passed.
3. The third parameter is the description of the option. This description will be used in the usage text of the application. When you will not give proper argument that time it will show like help command.
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse( options, args);
The parse methods of CommandLineParser are used to parse the command line arguments. The PosixPaser is great when you need to handle options that are one character long, like the t option in this example. Else use BasicParser for more than one character input.
Now we need to check if the t option is present. To do this we will interrogate the CommandLine object. The hasOption method takes a java.lang.String parameter and returns true if the option represented by the java.lang.String is present, otherwise it returns false.
if(cmd.hasOption("t")) {
// print the date and time
}
else {
// print the some thing else;
}
One complete example on CLI :
import org.apache.commons.cli.*;
public class CLIDemo{
public static void main(String args[]){
Options options = new Options();
options.addOption("n", true, "[name] your name");
Option timeOption = new Option("t", false, "current time");
options.addOption(timeOption);
// ** now lets parse the input
CommandLineParser parser = new BasicParser();
CommandLine cmd;
try{
cmd = parser.parse(options, args);
}catch (ParseException pe){ usage(options); return; }
// ** now lets interrogate the options and execute the relevant parts
if(cmd.hasOption("t")){
System.out.println("You have given argument is t");
System.err.println("Date/Time: " + new java.util.Date());
}
if(cmd.hasOption("n")){
System.out.println("You have given argument is n");
System.err.println("Nice to meet you: " + cmd.getOptionValue('n'));
}
}
private static void usage(Options options){
// Use the inbuilt formatter class
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp( "CLIDemo", options );
}
}
In the above code, there is no any use to use cmd.getOptionValue('t') with t condition, as t has been setup false and it would be never get any extra argument as n.
How to run CLI example:
D:\JavaTest>javac CLIDemo.java
D:\JavaTest>java CLIDemo
D:\JavaTest>java CLIDemo -t
You have given argument is t
Date/Time: Sun Apr 11 21:19:50 EEST 2010
D:\JavaTest>java CLIDemo -n
usage: CLIDemo
-n [name] your name
-t current time
D:\JavaTest>java CLIDemo -n Nik
You have given argument is n
Nice to meet you: Nik
D:\JavaTest>java CLIDemo -n "Nik Suman"
You have given argument is n
Nice to meet you: Nik Suman
D:\JavaTest>
First time I did not give any argument, so there is no any output.
Second time I gave -t as argument then we got output as per our expectation.
Third time I gave -n. This time, durint parsing the input it got error so execute catch part. Actually -n has been setup with true so we have to have some
extra argument with -n. In catch block we are printing the help format.
Forth time I gave -n With some name, so it worked perfectly.
Saturday, April 10, 2010
MAVEN getting started, Maven in 10 Minutes
Download
apache-maven-3.0-alpha-7-bin.zip and unzip into any where (In my case it is D:\Software\apache-maven-3.0-alpha-7)
set path D:\Software\apache-maven-3.0-alpha-7\bin
open dos console and type mvn -v
To check for sucessfully install.
Create one folder to practice for maven project say D:\binod\Maven_Practice
Now execute command from dos console
D:\binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.bds -DartifactId=CheckMaven
CheckMaven is the project name
command exectued from D:\binod\Maven_Practice
it create one folder CheckMaven inside D:\binod\Maven_PracticeInside CheckMaven : src folder and pom.xml file
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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies></project>
src -> main and test. main -> java -> com -> tecnotree -> bds -> App.javatest -> java -> com -> tecnotree -> bds -> AppTest.java
App.java
package com.tecnotree.bds;
public class App {
public static void main( String[] args ) {
System.out.println( "Hello World!" );
}
}
AppTest.java
package com.tecnotree.bds;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/** * Unit test for simple App. */
public class AppTest extends TestCase{
/** * Create the test case * * @param testName name of the test case */
public AppTest( String testName ) { super( testName ); }
/** * @return the suite of tests being tested */
public static Test suite() { return new TestSuite( AppTest.class ); }
/** * Rigourous Test :-) */
public void testApp() { assertTrue( true ); }
}
D:\Binod\Maven_Practice\CheckMaven> mvn compile
It compile App.java and create new folder target and App.class put into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bds
without running above commannd
D:\Binod\Maven_Practice\CheckMaven>mvn test-compile then it will compile App.java and AppTest.java and put App.class into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bdsand AppTest.java into D:\Binod\Maven_Practice\CheckMaven\target\test-classes\com\tecnotree\bds
without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn test
It will do mvn test-compile and extra test. Means in target there would be create three folderlike about classes and test-classes and new is surefire-report.
Actually mvn test it runs the compiled unit tests and make report (txt & xml) and put into surefire-report folder.
This command will also show test result on console.
D:\Binod\Maven_Practice\CheckMaven> mvn package
It would be work of mvn test and extra create one folder maven-archiver and put one jar file CheckMaven-1.0-SNAPSHOT.jar into target folder.
Inside the maven-archiver one pom.properties file would be come with these details:
#Generated by Maven#Sat Apr 10 10:34:57 EEST 2010version=1.0-SNAPSHOTgroupId=com.tecnotree.bdsartifactId=CheckMaven
D:\Binod\Maven_Practice\CheckMaven>mvn integration-test
It will execute all above command internally and carries out acutal integartion tests. Right now no any differences from above command. We will see later.
Without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn install
It will run above command interally and adds the archive to the local Maven directory. This makes it available for any other modules that may depend on it.
My local repository set up into D:\.m2 folder.
(How to set up custome local maven repository:
I have install or unzip Maven file here D:\Software\apache-maven-3.0-alpha-7. Go into D:\Software\apache-maven-3.0-alpha-7\conf and change settings.xml
uncommented <localRepository> and changed to <localRepository>D:\.m2\repository</localRepository>
so, CheckMaven-1.0-SNAPSHOT.jar put into D:\.m2\repository\com\tecnotree\bds\CheckMaven\1.0-SNAPSHOT
Without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn deploy
It will run above command interally and adds the archive to the remote Maven directory. But here it wont work.
Because we dont have set up the repository element was not specified in the pom inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]
How to set remote maven repository.
open pom.xml (D:\Binod\Maven_Practice\CheckMaven\pom.xml)
Add <distributionManagement> like this
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url>
</repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement>
</project>
Now you will see after run mvn deploy.
one target file will be created as usual and archieve file will go to d:/MyRemoteMavenRepository (no need to createthis folder, it create automatically).
D:\Binod\Maven_Practice\CheckMaven> mvn cleanIt will delete the target forlder.
************************ CONCLUSION ********************
There are phases of the default life cycle of Maven
1. validate : Ensures that the current configuration and the content of the POM is valid. This includes validation of the tress of pom.xml files.
2. compile : Compiles the source code. The compiled classes are places into a target directory tree.
3. test-compile : Compile the source code of the unit tests.
4. test: Runs the compiled unit tests and showing the result on the console.
5. package: Bundles the exectable binaries into a distribution archive, such as a JAR or WAR.
6. integration-test : Carries out actual integration tests.
7. install : Adds the archive to the local Maven directory. This markes it available for any other modules that may depends on it.
8. deploy : Adds the archive to a remote Maven directory. This can make the artifact available to a larger audience.
Concept is here that if you run 3 then it will run 1, 2 and 3.
if you run 6 then it will run 1,2,3,4,5 and 6.
That is because if you call a build phase, it will execute not only that build phase, but also every build phase prior to the called build phase.
It should also be noted that the same command can be used in a multi-module scenario (i.e. a project with one or more subprojects). For example:mvn clean install (from root directory), this command will traverse into all of the subprojects and run clean, then install (including all of the prior steps).
mvn install -Dmaven.test.skip=true : it will do install but except test execution.
How to integrate with Eclipse
Now if you want to import this project into eclipse, it will not work. In eclipse you would not be able to import this project.
D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:eclipse
It will create two file inside D:\Binod\Maven_Practice\CheckMaven folder. 1. .classpath and 2. .project. Now you can import into eclispe.
Open eclipse and set workplace is D:\Binod\Maven_Practice. File -> Import -> Import -> General -> Existing Projects into Workspace -> Browse (Select root directory, D:\Binod\Maven_Practice)then check CheckMaven -> Finish
Your project would be imported into workspace.
D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:cleanIt will delete both generated file 1. .classpath and 2. .project.
D:\Binod\Maven_Practice\CheckMaven>mvn eclipse:clean eclipse:eclipse
Now we ensured that all previous eclipse resources are removed and generated again.
To let eclipse know where the local Maven 2 repository is located you should know where it is located. By default the Maven 2 repository is located at
/home/[USERNAME]/.m2/repositoryC:\Documents and Settings\sumankbi\.m2\repository
We should avoid avoid space in maven repository class path. Refer above settign to change local repository.
In Eclipse -> window -> Preferences -> Maven -> Installation -> User setting -> Browse -> D:\Software\apache-maven-3.0-alpha-7\conf\settings.xml then Local repository will be change as per the setting.xml and it become D:\.m2\repository.
Now check, In Eclipse -> window -> Preferences -> Java -> Build Path -> Classpath Variable -> M2_REPO shold be D:\.m2\repository.
mvn clean eclipse:clean eclipse:eclipse
Dependencies
Some dependencies often are needed to write your applications. Commonly we are using some open source libraries and frameworks (e.g. the spring application framework or apache commons-logging,...). Sometimes own libraries should be referenced by a java project. To solve this problem Maven delivers a very good dependency mechanism that manages the dependencies of your project transitivly.
How the maven download new jar file, if our project is needed for that jar file.
Maven will download all dependencies referenced by your pom.xml from the central Maven 2 repository automatically to local reposity (In my case D:\.m2\repository). Suppose my project is needed commons-logging jar file then put this jar info into pom.xml and run mvn package and watch console, maven will downloading this jar into your local repository.
You have to add commons-logging into pom.xml
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency>
Now complete 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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url>
</repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement>
</project>
Even I changed junit from 3.1 to 4.5. Now if I run mvn command (mvn clean package), it will download both jar file. You can watch d:\.m2\repository and console both.
Some more example
<dependency>
<groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>2.5.5</version> </dependency> <dependency>
<groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>2.5.5</version>
</dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>2.5.5</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>2.5.5</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency>
</dependencies>
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency>
Properties : Same as Ant, we can set up any variable and use in the xml file.
In above example we are repeating same version number of all the spring jar file, so better put one place all the version number and use references. Use the properties tag.
<properties>
<spring-version>2.5.5</spring-version>
<junit-version>4.5</junit-version>
<commons-dbcp-version>1.2.2</commons-dbcp-version>
<commons-logging-version>1.1.1</commons-logging-version>
<mysql-version>5.1.6</mysql-version>
<servlet-version>1.1.2</servlet-version>
</properties>
<dependencies>
<!-- Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>
</dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${servlet-version}</version>
</dependency>
Scopes: The dependency scope defines to which part of the project's lifecycle the dependency is attached. For example the JUnit dependency is only added while running the tests. So i defined that this dependency is attached to the target "test".
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
</dependencies>
There are at least 6 different scopes:
compile: This scope indicates the Maven compilation phase. It is the default scope that will be used if no scope is defined. provided: This scope defines that this dependency is provided by the container (e.g. Apache Tomcat) at runtime. runtime: This scope indicates that this Dependency isn't required in the compilation phase but it is needed at runtime. test: "test"-dependencies are only while compiling and running the tests. system: This scope indicates that the dependency is provided by the system.
ABOUT POM.XML
you must always think of a Maven POM in terms of the combinationof the Super POM, plus any parent POMs, and finally the current project’s POM. Maven starts with theSuper POM and then overrides default configuration with one or more parent POMs. Then it overridesthe resulting configuration with the current project’s POM.
Build element: it that handles things like declaring your project's directory structure and managing plugins; and the reporting element, that largely mirrors the build element for reporting purposes.
MultiProject in Maven
Create one folder say (MultiProjectCheck) D:\Binod\Maven_Practice\MultiProjectCheck
execute this command:
D:\Binod\Maven_Practice\MultiProjectCheck>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=MultiProject
It will create MultiProject and put src and pom.xml.
Now go to pom.xml in D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xmland change <packaging>jar</packaging> to <packaging>pom</packaging>.
By setting the packaging type to “pom”, any projects you generate from the root of the project directory will insert itself into the project by creating an entry into the modules section of the pom.xml for the site.
Now execute this below both command from MultiProject folder.
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=FirstSubModule
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=SecondModule
Now come to D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xml (parent pom.xml), you will automatically added two module like this:
<modules>
<module>FirstSubModule</module> <module>SecondModule</module>
</modules>
You will see new tag in submodule pom.xml files.
<parent>
<artifactId>MultiProject</artifactId> <groupId>com.tecnotree.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
Now if you run mvn test from parent folder
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject
then it will create target forlder in both module. But if you run mvn test from insidet FirstSubModule folder then it will be creating only in this module, it wont effect on second module SecondModule.
How to import into Eclispe:
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn eclipse:eclipse
Create workspace in eclipse D:\Binod\Maven_Practice\MultiProjectCheck\MultiProjectand import -> browse -> select D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject -> It will show both project, select both project and it will come to eclipse.
How to develop Maven site.
Maven site example.
come to D:\Binod\Maven_Practice
D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheckand
execute this command to generate site folder inside src
D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-site -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheck
go to D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml
Here you can write about your project.
Now,
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site
It will create one target folder in D:\Binod\Maven_Practice\MavenSiteCheck.
One html file generate D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.htmlyou can open this html file.
You can also run this page as web site using jetty
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:runURL: http://localhost:8080/xdoc.html
How you can put some picture here in documentcreate one resources inside the site folder (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources) and put all your picutre here say suman.jpg
now come to xdoc.xml (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml)
and write here <img src="suman.jpg"></img>
Now,
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site
It will move all the images from D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources to D:\Binod\Maven_Practice\MavenSiteCheck\target\site.
now open D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.html
apache-maven-3.0-alpha-7-bin.zip and unzip into any where (In my case it is D:\Software\apache-maven-3.0-alpha-7)
set path D:\Software\apache-maven-3.0-alpha-7\bin
open dos console and type mvn -v
To check for sucessfully install.
Create one folder to practice for maven project say D:\binod\Maven_Practice
Now execute command from dos console
D:\binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.bds -DartifactId=CheckMaven
CheckMaven is the project name
command exectued from D:\binod\Maven_Practice
it create one folder CheckMaven inside D:\binod\Maven_PracticeInside CheckMaven : src folder and pom.xml file
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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies></project>
src -> main and test. main -> java -> com -> tecnotree -> bds -> App.javatest -> java -> com -> tecnotree -> bds -> AppTest.java
App.java
package com.tecnotree.bds;
public class App {
public static void main( String[] args ) {
System.out.println( "Hello World!" );
}
}
AppTest.java
package com.tecnotree.bds;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/** * Unit test for simple App. */
public class AppTest extends TestCase{
/** * Create the test case * * @param testName name of the test case */
public AppTest( String testName ) { super( testName ); }
/** * @return the suite of tests being tested */
public static Test suite() { return new TestSuite( AppTest.class ); }
/** * Rigourous Test :-) */
public void testApp() { assertTrue( true ); }
}
D:\Binod\Maven_Practice\CheckMaven> mvn compile
It compile App.java and create new folder target and App.class put into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bds
without running above commannd
D:\Binod\Maven_Practice\CheckMaven>mvn test-compile then it will compile App.java and AppTest.java and put App.class into D:\Binod\Maven_Practice\CheckMaven\target\classes\com\tecnotree\bdsand AppTest.java into D:\Binod\Maven_Practice\CheckMaven\target\test-classes\com\tecnotree\bds
without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn test
It will do mvn test-compile and extra test. Means in target there would be create three folderlike about classes and test-classes and new is surefire-report.
Actually mvn test it runs the compiled unit tests and make report (txt & xml) and put into surefire-report folder.
This command will also show test result on console.
D:\Binod\Maven_Practice\CheckMaven> mvn package
It would be work of mvn test and extra create one folder maven-archiver and put one jar file CheckMaven-1.0-SNAPSHOT.jar into target folder.
Inside the maven-archiver one pom.properties file would be come with these details:
#Generated by Maven#Sat Apr 10 10:34:57 EEST 2010version=1.0-SNAPSHOTgroupId=com.tecnotree.bdsartifactId=CheckMaven
D:\Binod\Maven_Practice\CheckMaven>mvn integration-test
It will execute all above command internally and carries out acutal integartion tests. Right now no any differences from above command. We will see later.
Without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn install
It will run above command interally and adds the archive to the local Maven directory. This makes it available for any other modules that may depend on it.
My local repository set up into D:\.m2 folder.
(How to set up custome local maven repository:
I have install or unzip Maven file here D:\Software\apache-maven-3.0-alpha-7. Go into D:\Software\apache-maven-3.0-alpha-7\conf and change settings.xml
uncommented <localRepository> and changed to <localRepository>D:\.m2\repository</localRepository>
so, CheckMaven-1.0-SNAPSHOT.jar put into D:\.m2\repository\com\tecnotree\bds\CheckMaven\1.0-SNAPSHOT
Without running any above command
D:\Binod\Maven_Practice\CheckMaven> mvn deploy
It will run above command interally and adds the archive to the remote Maven directory. But here it wont work.
Because we dont have set up the repository element was not specified in the pom inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter -> [Help 1]
How to set remote maven repository.
open pom.xml (D:\Binod\Maven_Practice\CheckMaven\pom.xml)
Add <distributionManagement> like this
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url>
</repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement>
</project>
Now you will see after run mvn deploy.
one target file will be created as usual and archieve file will go to d:/MyRemoteMavenRepository (no need to createthis folder, it create automatically).
D:\Binod\Maven_Practice\CheckMaven> mvn cleanIt will delete the target forlder.
************************ CONCLUSION ********************
There are phases of the default life cycle of Maven
1. validate : Ensures that the current configuration and the content of the POM is valid. This includes validation of the tress of pom.xml files.
2. compile : Compiles the source code. The compiled classes are places into a target directory tree.
3. test-compile : Compile the source code of the unit tests.
4. test: Runs the compiled unit tests and showing the result on the console.
5. package: Bundles the exectable binaries into a distribution archive, such as a JAR or WAR.
6. integration-test : Carries out actual integration tests.
7. install : Adds the archive to the local Maven directory. This markes it available for any other modules that may depends on it.
8. deploy : Adds the archive to a remote Maven directory. This can make the artifact available to a larger audience.
Concept is here that if you run 3 then it will run 1, 2 and 3.
if you run 6 then it will run 1,2,3,4,5 and 6.
That is because if you call a build phase, it will execute not only that build phase, but also every build phase prior to the called build phase.
It should also be noted that the same command can be used in a multi-module scenario (i.e. a project with one or more subprojects). For example:mvn clean install (from root directory), this command will traverse into all of the subprojects and run clean, then install (including all of the prior steps).
mvn install -Dmaven.test.skip=true : it will do install but except test execution.
How to integrate with Eclipse
Now if you want to import this project into eclipse, it will not work. In eclipse you would not be able to import this project.
D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:eclipse
It will create two file inside D:\Binod\Maven_Practice\CheckMaven folder. 1. .classpath and 2. .project. Now you can import into eclispe.
Open eclipse and set workplace is D:\Binod\Maven_Practice. File -> Import -> Import -> General -> Existing Projects into Workspace -> Browse (Select root directory, D:\Binod\Maven_Practice)then check CheckMaven -> Finish
Your project would be imported into workspace.
D:\Binod\Maven_Practice\CheckMaven> mvn eclipse:cleanIt will delete both generated file 1. .classpath and 2. .project.
D:\Binod\Maven_Practice\CheckMaven>mvn eclipse:clean eclipse:eclipse
Now we ensured that all previous eclipse resources are removed and generated again.
To let eclipse know where the local Maven 2 repository is located you should know where it is located. By default the Maven 2 repository is located at
/home/[USERNAME]/.m2/repositoryC:\Documents and Settings\sumankbi\.m2\repository
We should avoid avoid space in maven repository class path. Refer above settign to change local repository.
In Eclipse -> window -> Preferences -> Maven -> Installation -> User setting -> Browse -> D:\Software\apache-maven-3.0-alpha-7\conf\settings.xml then Local repository will be change as per the setting.xml and it become D:\.m2\repository.
Now check, In Eclipse -> window -> Preferences -> Java -> Build Path -> Classpath Variable -> M2_REPO shold be D:\.m2\repository.
mvn clean eclipse:clean eclipse:eclipse
Dependencies
Some dependencies often are needed to write your applications. Commonly we are using some open source libraries and frameworks (e.g. the spring application framework or apache commons-logging,...). Sometimes own libraries should be referenced by a java project. To solve this problem Maven delivers a very good dependency mechanism that manages the dependencies of your project transitivly.
How the maven download new jar file, if our project is needed for that jar file.
Maven will download all dependencies referenced by your pom.xml from the central Maven 2 repository automatically to local reposity (In my case D:\.m2\repository). Suppose my project is needed commons-logging jar file then put this jar info into pom.xml and run mvn package and watch console, maven will downloading this jar into your local repository.
You have to add commons-logging into pom.xml
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency>
Now complete 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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tecnotree.bds</groupId> <artifactId>CheckMaven</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>CheckMaven</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <scope>test</scope> </dependency> </dependencies> <distributionManagement> <repository> <id>BinodprojectRepository</id> <name>Binod Maven Repository Name</name> <url>file:///d:/MyRemoteMavenRepository</url>
</repository> <!-- site> <id>sample-project.website</id> <url>dav:https://dav.sample.com/sites/sample-project</url> </site --> </distributionManagement>
</project>
Even I changed junit from 3.1 to 4.5. Now if I run mvn command (mvn clean package), it will download both jar file. You can watch d:\.m2\repository and console both.
Some more example
<dependency>
<groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>2.5.5</version> </dependency> <dependency>
<groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>2.5.5</version>
</dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>2.5.5</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>2.5.5</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency>
</dependencies>
<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency>
Properties : Same as Ant, we can set up any variable and use in the xml file.
In above example we are repeating same version number of all the spring jar file, so better put one place all the version number and use references. Use the properties tag.
<properties>
<spring-version>2.5.5</spring-version>
<junit-version>4.5</junit-version>
<commons-dbcp-version>1.2.2</commons-dbcp-version>
<commons-logging-version>1.1.1</commons-logging-version>
<mysql-version>5.1.6</mysql-version>
<servlet-version>1.1.2</servlet-version>
</properties>
<dependencies>
<!-- Spring Framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>
</dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${servlet-version}</version>
</dependency>
Scopes: The dependency scope defines to which part of the project's lifecycle the dependency is attached. For example the JUnit dependency is only added while running the tests. So i defined that this dependency is attached to the target "test".
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
</dependencies>
There are at least 6 different scopes:
compile: This scope indicates the Maven compilation phase. It is the default scope that will be used if no scope is defined. provided: This scope defines that this dependency is provided by the container (e.g. Apache Tomcat) at runtime. runtime: This scope indicates that this Dependency isn't required in the compilation phase but it is needed at runtime. test: "test"-dependencies are only while compiling and running the tests. system: This scope indicates that the dependency is provided by the system.
ABOUT POM.XML
you must always think of a Maven POM in terms of the combinationof the Super POM, plus any parent POMs, and finally the current project’s POM. Maven starts with theSuper POM and then overrides default configuration with one or more parent POMs. Then it overridesthe resulting configuration with the current project’s POM.
Build element: it that handles things like declaring your project's directory structure and managing plugins; and the reporting element, that largely mirrors the build element for reporting purposes.
MultiProject in Maven
Create one folder say (MultiProjectCheck) D:\Binod\Maven_Practice\MultiProjectCheck
execute this command:
D:\Binod\Maven_Practice\MultiProjectCheck>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=MultiProject
It will create MultiProject and put src and pom.xml.
Now go to pom.xml in D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xmland change <packaging>jar</packaging> to <packaging>pom</packaging>.
By setting the packaging type to “pom”, any projects you generate from the root of the project directory will insert itself into the project by creating an entry into the modules section of the pom.xml for the site.
Now execute this below both command from MultiProject folder.
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=FirstSubModule
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.tecnotree.mp -DartifactId=SecondModule
Now come to D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject\pom.xml (parent pom.xml), you will automatically added two module like this:
<modules>
<module>FirstSubModule</module> <module>SecondModule</module>
</modules>
You will see new tag in submodule pom.xml files.
<parent>
<artifactId>MultiProject</artifactId> <groupId>com.tecnotree.mp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
Now if you run mvn test from parent folder
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject
then it will create target forlder in both module. But if you run mvn test from insidet FirstSubModule folder then it will be creating only in this module, it wont effect on second module SecondModule.
How to import into Eclispe:
D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject>mvn eclipse:eclipse
Create workspace in eclipse D:\Binod\Maven_Practice\MultiProjectCheck\MultiProjectand import -> browse -> select D:\Binod\Maven_Practice\MultiProjectCheck\MultiProject -> It will show both project, select both project and it will come to eclipse.
How to develop Maven site.
Maven site example.
come to D:\Binod\Maven_Practice
D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheckand
execute this command to generate site folder inside src
D:\Binod\Maven_Practice>mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-site -DgroupId=com.mycompany.app -DartifactId=MavenSiteCheck
go to D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml
Here you can write about your project.
Now,
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site
It will create one target folder in D:\Binod\Maven_Practice\MavenSiteCheck.
One html file generate D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.htmlyou can open this html file.
You can also run this page as web site using jetty
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:runURL: http://localhost:8080/xdoc.html
How you can put some picture here in documentcreate one resources inside the site folder (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources) and put all your picutre here say suman.jpg
now come to xdoc.xml (D:\Binod\Maven_Practice\MavenSiteCheck\src\site\xdoc\xdoc.xml)
and write here <img src="suman.jpg"></img>
Now,
D:\Binod\Maven_Practice\MavenSiteCheck>mvn site:site
It will move all the images from D:\Binod\Maven_Practice\MavenSiteCheck\src\site\resources to D:\Binod\Maven_Practice\MavenSiteCheck\target\site.
now open D:\Binod\Maven_Practice\MavenSiteCheck\target\site\xdoc.html
Subscribe to:
Posts (Atom)