Thursday, 10 July 2008

Spring Hibernate

Account.java
.....................

package springexample.hibernate;

import java.math.BigDecimal;
import java.util.Date;

public class Account {

private Long id = new Long(-1);

private String accountName;

private String type;

private Double balance;

private Date createDate;

private Date updateDate;

private Customer customer;

public String getAccountName() {
return accountName;
}


public void setAccountName(String accountName) {
this.accountName = accountName;
}



public Date getCreateDate() {
return createDate;
}


public void setCreateDate(Date createDate) {
this.createDate = createDate;
}


public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}


public String getType() {
return type;
}


public void setType(String type) {
this.type = type;
}


public Date getUpdateDate() {
return updateDate;
}


public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}


public Customer getCustomer() {
return customer;
}



public void setCustomer(Customer customer) {
this.customer = customer;
}

public Double getBalance() {
return balance;
}

public void setBalance(Double balance) {
this.balance = balance;
}

}



AccountDAO.java
.............................
package springexample.hibernate;

import java.util.List;


public interface AccountDAO {

public abstract void addAccount(Account account);
}

AccountDAOImpl.java
...................................

package springexample.hibernate;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;

import org.springframework.orm.hibernate.HibernateCallback;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;


public class AccountDAOImpl extends HibernateDaoSupport implements AccountDAO{

public void addAccount(Account account) {
getHibernateTemplate().save(account);
// TODO Auto-generated method stub

}

}


customer.java
................
package springexample.hibernate;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;

public class Customer {

private Long id = new Long(-1);
private String userId;
private String password;
private String email;
private String firstName;
private String lastName;
private BigDecimal balance;

private Set accounts = new HashSet();

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}



public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}

public Set getAccounts() {
return accounts;
}


public void setAccounts(Set accounts) {
this.accounts = accounts;
}

public void addAccount(Account account){
account.setCustomer(this);
accounts.add(account);
}

public BigDecimal getBalance() {
return balance;
}


public void setBalance(BigDecimal balance) {
this.balance = balance;
}


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;
}

public String getUserId() {
return userId;
}


public void setUserId(String userId) {
this.userId = userId;
}


}

CustomerDAO.java
.................

package springexample.hibernate;

import java.util.List;

public interface CustomerDAO {

public abstract void addCustomer(Customer customer);

public abstract Customer getCustomerAccountInfo(Customer customer);
}
 
CustomerDAOImpl.java
.................
package springexample.hibernate;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import org.springframework.orm.hibernate.HibernateCallback;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;
public class CustomerDAOImpl extends HibernateDaoSupport implements CustomerDAO{
public void addCustomer(Customer customer) { getHibernateTemplate().save(customer); // TODO Auto-generated method stub
}
public Customer getCustomerAccountInfo(Customer customer) { Customer cust = null;
List list = getHibernateTemplate().find("from Customer customer " +"where customer.userId = ?" , customer.getUserId(),Hibernate.STRING);
if(list.size() > 0){
cust = (Customer) list.get(0);
}
return cust;
}
}

CreateBankCustomerClient.java
..............................
package springexample.hibernate;
import java.util.ArrayList;
import java.util.Date;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.orm.hibernate.LocalSessionFactoryBean;
public class CreateBankCustomerClient {
public static ClassPathXmlApplicationContext appContext = null;
public static void main(String[] args){
try {
System.out.println("CreateBankCustomerClient started"); ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { "springexample-hibernate.xml" }); System.out.println("Classpath loaded");
Customer customer = new Customer(); customer.setEmail("anil.goud@cellarch.com.com"); customer.setUserId("anilkumar"); customer.setPassword("xxxxx");
customer.setFirstName("anil");
customer.setLastName("goud");
Account acc = new Account();
acc.setAccountName("Checking Account-Raj Malhotra"); acc.setType("C");
acc.setCreateDate(new Date());
acc.setUpdateDate(new Date());
acc.setBalance(new Double(500.00));
customer.addAccount(acc);
CustomerDAOImpl customerDAOImpl = (CustomerDAOImpl) appContext.getBean("customerDAOTarget"); customerDAOImpl.addCustomer(customer);
Customer customerRecord = customerDAOImpl.getCustomerAccountInfo(customer);
System.out.println("Customer Found , User Id is " + customerRecord.getUserId());

System.out.println("CreateBankCustomerClient end");
} catch(Exception e){
e.printStackTrace();
}
}
private static void createDatabaseSchema() throws Exception { LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean) appContext.getBean("&frameworkSessionFactory"); sessionFactory.dropDatabaseSchema(); sessionFactory.createDatabaseSchema();
}
}


Account.hbm.xml
................

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping>
<class name="springexample.hibernate.Account" table="TBL_ACCOUNT" dynamic-update="false" dynamic-insert="false">
<id name="id" column="ACCOUNT_ID"
type="java.lang.Long" unsaved-value="-1" >
<generator class="native">
</generator> </id>
<many-to-one name="customer"
column="CUSTOMER_ID" class="springexample.hibernate.Customer"
not-null="true"/>
<property name="accountName" type="string"
update="false" insert="true" column="ACCOUNT_NAME"
length="50" not-null="true" />
<property name="type" type="string" update="false" insert="true" column="ACCOUNT_TYPE" length="1" not-null="true" />
<property name="createDate" type="date"
update="false" insert="true" column="CREATE_DATE" not-null="true" />
<property name="updateDate" type="date" update="true" insert="true" not-null="true" column="UPDATE_DATE" /> <property name="balance" type="double" update="true" insert="true"
column="ACCOUNT_BALANCE" not-null="true"/> </class>
</hibernate-mapping>


Customer.hbm.xml
......................


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping>
<class name="springexample.hibernate.Customer" table="TBL_CUSTOMER" dynamic-update="false" dynamic-insert="false"> <id name="id" column="CUSTOMER_ID" type="java.lang.Long" unsaved-value="-1" > <generator class="native"> </generator> </id> <set name ="accounts" inverse = "true" cascade="all-delete-orphan"> <key column ="CUSTOMER_ID"/> <one-to-many class="springexample.hibernate.Account"/> </set> <property name="email" type="string" update="false" insert="true" column="CUSTOMER_EMAIL" length="82" not-null="true" /> <property name="password" type="string" update="false" insert="true" column="CUSTOMER_PASSWORD" length="10" not-null="true" /> <property name="userId" type="string" update="false" insert="true" column="CUSTOMER_USERID" length="12" not-null="true" unique="true" /> <property name="firstName" type="string" update="false" insert="true" column="CUSTOMER_FIRSTNAME" length="25" not-null="true" /> <property name="lastName" type="string" update="false" insert="true" column="CUSTOMER_LASTTNAME" length="25" not-null="true" /> </class> </hibernate-mapping>


springexample-hibernate.xml
.............................


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <!-- - Application context definition for Express on Hibernate. --> <beans> <bean id="exampleDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"><value>org.apache.derby.jdbc.EmbeddedDriver
</value></property>
<property name="url"><value>jdbc:derby:springexample;create=true</value></property> </bean> <bean id="exampleHibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.dialect">net.sf.hibernate.dialect.DerbyDialect</prop> <prop key="hibernate.query.substitutions">true 'T', false 'F'</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.c3p0.minPoolSize">5</prop> <prop key="hibernate.c3p0.maxPoolSize">20</prop> <prop key="hibernate.c3p0.timeout">600</prop> <prop key="hibernate.c3p0.max_statement">50</prop> <prop key="hibernate.c3p0.testConnectionOnCheckout">false</prop> </props> </property> </bean> <!-- Hibernate SessionFactory --> <bean id="exampleSessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="dataSource"><ref local="exampleDataSource"/></property> <property name="hibernateProperties"> <ref bean="exampleHibernateProperties" /> </property> <!-- Must references all OR mapping files. --> <property name="mappingResources"> <list> <value>Customer.hbm.xml</value> <value>Account.hbm.xml</value> </list> </property> </bean> <!-- Pass the session factory to our UserDAO --> <bean id="customerDAOTarget" class="springexample.hibernate.CustomerDAOImpl"> <property name="sessionFactory"><ref local="exampleSessionFactory"/></property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> <property name="sessionFactory"><ref bean="exampleSessionFactory"/></property> </bean> <bean id="userDAO" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"><ref local="transactionManager"/></property> <property name="target"><ref local="customerDAOTarget"/></property> <property name="transactionAttributes"> <props> <prop key="addCustomer">PROPAGATION_REQUIRED</prop> </props> </property> </bean> </beans>

build.xml
............

<project name="springexamples" basedir="." default="main"> <property name="src.dir" value="src"/> <property name="springconf.files" value="src/spring"/> <property name="build.dir" value="build"/> <property name="classes.dir" value="${build.dir}/classes"/> <property name="jar.dir" value="${build.dir}/jar"/> <property name="main-class" value="springexample.hibernate.CreateBankCustomerClient"/> <property name="lib.dir" value="lib"/> <property name="common-lib.dir" value ="C:\spring-framework-1.2-rc2\lib\jakarta-commons"/> <property name="ecache-lib.dir" value ="C:\spring-framework-1.2-rc2\lib\ehcache"/> <property name="dom4j-lib.dir" value ="C:\spring-framework-1.2-rc2\lib\dom4j"/> <property name="cglib-lib.dir" value ="C:\spring-framework-1.2-rc2\lib\cglib"/> <property name="hibernate-lib.dir" value ="C:\spring-framework-1.2-rc2\lib\hibe rnate"/> <property name="jta-lib.dir" value ="C:\spring-framework-1.2-rc2\lib\j2ee"/> <property name="spring-lib.dir" value ="C:\spring-framework-1.2-rc2\dist"/> <property name="ojb-lib.dir" value ="C:\spring-framework-1.2-rc2\lib\ojb"/> <property name="derby-lib.dir" value ="C:\Program Files\IBM\Cloudscape_10.0\lib"/> <path id="classpath"> <fileset dir="${lib.dir}" includes="**/*.jar"/> <fileset dir="${common-lib.dir}" includes="**/*.jar"/> <fileset dir="${ecache-lib.dir}" includes="**/*.jar"/> <fileset dir="${dom4j-lib.dir}" includes="**/*.jar"/> <fileset dir="${cglib-lib.dir}" includes="**/*.jar"/> <fileset dir="${hibernate-lib.dir}" includes="**/*.jar"/> <fileset dir="${jta-lib.dir}" includes="**/*.jar"/> <fileset dir="${spring-lib.dir}" includes="**/*.jar"/> <fileset dir="${ojb-lib.dir} " includes="**/*.jar"/> <fileset dir="${derby-lib.dir}" includes="**/*.jar"/> <path location="${springconf.files}"/> </path> <target name="clean"> <delete dir="${build.dir}"/> </target> <target name="compile"> <mkdir dir="${classes.dir}"/> <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/> </target> <target name="jar" depends="compile"> <mkdir dir="${jar.dir}"/> <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}"> <manifest> <attribute name="Main-Class" value="${main-class}"/> </manifest> </jar> </target> <target name="run" depends="jar"> <java fork="true" classname="${main-class}"> <classpath> <path refid="classpath"/> <path location="${jar.dir}/${ant.project.name}.jar"/> </classpath> </java> </target> <target name="clean-build" depends="clean,jar"/> <target name="main" depends="clean,run"/> </project>







No comments:

Post a Comment