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.
Tuesday, July 13, 2010
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 ..... :)
Subscribe to:
Posts (Atom)