Thursday, June 20, 2013

Spring Hibernate: web/index.jsp


<meta http-equiv="refresh" content="1; url=/bookStore/addBook"/>

Spring Hibernate: bookstore.service.BookServiceImpl.java


package bookstore.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import bookstore.dao.BaseDao;
import bookstore.domain.Book;


@Service ("bookService")
public class BookServiceImpl implements BookService {

@Autowired
BaseDao baseDao;

@Override
public void persist(Book book) {
baseDao.persist(book);

}

@Override
public List<Book> getAll() {

return baseDao.getAll(Book.class);
}

}

Spring Hibernate: bookstore.service.BookService.java


package bookstore.service;

import java.util.List;

import bookstore.domain.Book;

public interface BookService {

public void persist(Book book);

public List<Book> getAll();
}

Spring Hibernate: bookstore.domain.Book.java


package bookstore.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;


@Entity (name = "book")
public class Book {

@Id
@GeneratedValue
private int bookId;

@NotNull
@Size (min = 2, max = 20)
private String title;

@DecimalMin (value = "2.0")
@DecimalMax (value = "100.0")
private double price;


public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}


}

Spring Hibernate: bookstore.dao.BaseDaoImpl.java


package bookstore.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository ( value = "baseDao")
@Transactional
public class BaseDaoImpl implements BaseDao {

@PersistenceContext
private EntityManager em;

@Override
public void persist(Object obj) {
em.persist(obj);

}

@Override
public <T> List<T> getAll(Class<T> clazz) {
       TypedQuery<T> query = em.createQuery(" from " + clazz.getName(), clazz);
  return query.getResultList();
}

}

Spring Hibernate: bookstore.dao.BaseDao.java


package bookstore.dao;

import java.util.List;

public interface BaseDao {

public void persist(Object obj);

public <T> List<T> getAll(Class<T> clazz);

}

Spring Hibernate: bookstore.controller.BookController.java


package bookstore.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import bookstore.domain.Book;
import bookstore.service.BookService;


@Controller
@RequestMapping ("/*")
public class BookController {

@Autowired
BookService bookService;

@RequestMapping (value = "/addBook", method=RequestMethod.GET)
public ModelAndView addBook() {
Book b1 = new Book();
b1.setTitle("book name");
return new ModelAndView ("addBook", "book", b1);
}

@RequestMapping (value = "/saveBook", method=RequestMethod.POST)
public String saveBook(@Valid Book book, BindingResult result,  ModelMap model) {
if (result.hasErrors()) {
return "addBook";
} else {
 bookService.persist(book);
 model.put("allBooks", bookService.getAll());
 return "listBooks";
}
}

@RequestMapping (value = "/abc", method=RequestMethod.GET)
public ModelAndView anyName() {
Book book1 = new Book();
book1.setTitle("Tale of Two Cities");
return new ModelAndView("addBook", "xyz", book1);
}


}

OOD Video Source


package oodDemo;

public abstract class Account {
private String name;
private double balance;

public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public Account() {}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void displayInfo() {
System.out.println("Name: " + name + " Balance: " + balance);
}
public abstract void deposit(double amount);

}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

package oodDemo;

public class Checking extends Account {
public Checking(String name, double amount) {
      super(name, amount); 
}

public void deposit(double amount) {
setBalance (getBalance() + amount);
}

}

~~~~~~~~~~~~~~~~~~~

package oodDemo;

public class oodApp {

/**
* @param args
*/
public static void main(String[] args) {

      Account acct1 = new Checking("john", 100.0d);
      Account acct2 = new Saving("Jane", 100.0d);
      
      acct1.deposit(100);
      acct2.deposit(100);
      
      acct1.displayInfo();
      acct2.displayInfo();
      
}

}
~~~~~~~~~~~~~~~~

package oodDemo;

public class Saving extends Account {

public Saving(String name, double amount) {
       super(name,amount);
}

public void deposit(double amount) {
setBalance (getBalance() + (amount * 1.10));
}

}

~~~~~~~~~~~~~~~~~~~~~

Spring Hibernate - web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>bookStore</display-name>
 <!-- Context loader -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 
     <!-- Spring MVC : will look for xml file: /WEB-INF/spring-mvc-servlet.xml -->
   <servlet>
     <servlet-name>spring-mvc</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
     <servlet-name>spring-mvc</servlet-name>
     <url-pattern>/</url-pattern>
   </servlet-mapping>
 
   <servlet-mapping>
       <servlet-name>default</servlet-name>
       <url-pattern>*.css</url-pattern>
   </servlet-mapping>
 
  <!-- Welcome File -->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
 
</web-app>

Spring Hibernate - spring-mvc-servlet.xml


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
           
    <mvc:annotation-driven/>
    <context:component-scan base-package="bookstore.controller" />  
   
    <!--  View: /approot<PREFIX>VIEWNAME<SUFFIX> -->
    <!--  View: /approot/WEB-INF/views/addBook.jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix"> <value>/WEB-INF/views/</value> </property>
    <property name="suffix"> <value>.jsp</value></property>
    </bean>  

     <bean class="org.springframework.context.support.ResourceBundleMessageSource"
        id="messageSource">
        <property name="basename" value="messages" />
    </bean>
   
</beans>

Spring Hibernate - bookstore.css


body { background: #EDDD82; }
table, th, td {
  border: 1px solid black;
  background-color:lightblue;
}
.error { color: #ff0000; }
.errorblock {position:absolute; left:50px; top:30px;
    color: #000; background-color: #ffEEEE;
 border: 3px solid #ff0000; padding: 8px; margin: 8px;}

Spring Hibernate - messages.properties


NotEmpty.book.title = Book title is required!
Size.book.title = Book title should be between 2 and 20 characters
DecimalMax.book.price = Price less than $100.00
DecimalMin.book.price = Price should be greater than $2.00

Spring Hibernate Tutorial - Application Config


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:amq="http://activemq.apache.org/schema/core"
  xmlns:jms="http://www.springframework.org/schema/jms"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/jee
            http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
            http://activemq.apache.org/schema/core
            http://activemq.apache.org/schema/core/activemq-core-5.5.0.xsd
            http://www.springframework.org/schema/jms
            http://www.springframework.org/schema/jms/spring-jms-2.5.xsd">

  <context:annotation-config />
  <context:component-scan base-package="bookstore" />
  <tx:annotation-driven />
  <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
  <bean id="dataSource1"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"> <value>org.gjt.mm.mysql.Driver</value></property>
    <property name="url"> <value>jdbc:mysql://localhost/test</value> </property>
    <property name="username"><value>test1</value> </property>
    <property name="password"><value>test2</value></property>
  </bean>
 
  <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource1"
    p:persistenceUnitName="BookJpaPersistenceUnit"/>
 
  <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
 
  <bean id="transactionManager"
          class="org.springframework.orm.jpa.JpaTransactionManager"
          p:entityManagerFactory-ref="entityManagerFactory"/>
 
  <tx:annotation-driven transaction-manager="transactionManager"/>
   
</beans>

Spring Tutorial Part 2 - Object creation, constructor-args, property injection


<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">        
  <context:annotation-config/>
  <context:component-scan base-package="springapp.beans"/>
 
  <!-- BEAN-1 -->
  <bean id="address1" class="springapp.beans.Address">
      <property name="city" value="Chicago"/>
      <property name="state" value="Illinois"/>
  </bean>
   
  <!--BEAN-2 CONSTRUCTOR_ARG name, type, ref Example-->
  <bean name="house2" class="springapp.beans.House" >
    <constructor-arg name="owner" value="CONS_ARG_name_type_ref" />      
    <constructor-arg type="double" value="122334.56" />
    <constructor-arg ref="address1"/>
  </bean>

    <!--BEAN-3 CONSTRUCTOR_ARG index, inner-bean Example-->
  <bean name="house3" class="springapp.beans.House" >
    <constructor-arg index="0" value="CONS_ARG_index-innerbean" />      
    <constructor-arg index="1" value="32322.45" />
    <constructor-arg>
        <bean class="springapp.beans.Address">
            <property name="city" value="Houston"/>
            <property name="state" value="Texas"/>
        </bean>
    </constructor-arg>
  </bean>
 
 <!--BEAN-4 PROPERTY Injection Example-->
   <bean name="house4" class="springapp.beans.House" >
    <constructor-arg index="0" value="PROP_INJ_HOUSE" />      
    <property name="price" value="82356.22" />
    <property name="features">
      <list value-type="java.lang.String">
       <value>Dishwasher</value>
       <value>Garage</value>
       <value>Patio</value>
     </list>
    </property>
    <property name="address" ref="address1"/>
  </bean>
 
 </beans>