Thursday, September 1, 2011

Passing an array to Oracle PL/SQL from Spring and MyBatis

1. Create an oracle type

CREATE OR REPLACE TYPE "VARCHAR2_TABLE" as table of varchar2(4000);
2. Access it
type c_cursor is ref cursor;
Procedure sp_test(p_codes IN varchar2_table, p_cursor out c_cursor) as
..Do processing.
Return ref cursor back
end sp_test
3. In Spring create a class called StringArrayTypeHandlerCallBack
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

public class StringArrayTypeHandlerCallBack implements TypeHandler {
/* @SuppressWarnings("unchecked")
public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
if(parameter == null) {
setter.setNull(Types.ARRAY);
}
else if(parameter instanceof ArrayList) {
Statement stmt = setter.getPreparedStatement();
Connection nativeConnection = (Connection) WSJdbcUtil.getNativeConnection((WSJdbcConnection) stmt.getConnection());
ArrayDescriptor desc = ArrayDescriptor.createDescriptor("NUMBER_ARRAY", nativeConnection);
parameter = new ARRAY(desc, nativeConnection, ((ArrayList) parameter).toArray());
}
setter.setObject(parameter);
}*/

public Object valueOf(String arg0) {
return null;
}

@Override
public Object getResult(ResultSet arg0, String arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public Object getResult(CallableStatement arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return null;
}

@Override
public void setParameter(PreparedStatement ps, int i, Object parameter,
JdbcType arg3) throws SQLException {

Connection conn = ps.getConnection();
// TODO Auto-generated method stub
ArrayDescriptor desc = ArrayDescriptor.createDescriptor("VARCHAR2_TABLE", conn);
parameter = new ARRAY(desc, conn, ((ArrayList) parameter).toArray());
ps.setArray(i, (oracle.sql.ARRAY)parameter);
}

}
Mybatis Configuration.(Mapper File)- Lets call it DataMapper.xml
>
call sp_test(
#{codes,mode=IN,typeHandler=com.usps.eems.common.StringArrayTypeHandlerCallBack}
,#{data,mode=OUT,jdbcType=CURSOR,javaType=java.sql.ResultSet,resultMap=resultOutMap}
)

Service Class
public void test(List codes){
Map map = new HashMap();
if(null!=codes)
map.put("codes", codes);
dataMapper.
test
(map);
}

Thats it.

Friday, March 18, 2011

Hibernate Basics Part 1

Automatic dirty checking

Person class has many events.

aPerson.getEvents().add(anEvent);

session.getTransaction().commit();

After loading a Person and an Event, simply modify the collection using the normal collection

methods. There is no explicit call to update() or save(); Hibernate automatically detects that the collection has been modified and needs to be updated. This is called automatic dirty checking. The process of synchronizing the memory state with the database, usually only at the end of a unit of work, is called flushing.

Updating data which is detached

// End of first unit of work

aPerson.getEvents().add(anEvent); // aPerson (and its collection) is detached

// Begin second unit of work

Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();

session2.beginTransaction();

session2.update(aPerson); // Reattachment of aPerson

session2.getTransaction().commit();

Inverse=”true”

Person class has a Set collection of participants

What this means is that Hibernate should take the other side, the Person class, when it needs to

find out information about the link between the two.

For you, and for Java, a bi-directional link is simply a matter of setting the references on both sides correctly. Hibernate, however, does not have enough information to correctly arrange SQL INSERT and UPDATE statements (to avoid constraint violations). Making one side of the association inverse tells Hibernate to consider it a mirror of the other side. That is all that is necessary for Hibernate to resolve any issues that arise when transforming a directional navigation model to a SQL database schema. The rules are straightforward: all bi-directional associations need one side as inverse. In a one-to-many association it has to be the many-side, and in many-to-many association you can select either side

Session-per-request

When a request hits the servlet, a new Hibernate Session is opened through the first call to getCurrentSession() on the SessionFactory. A database transaction is then started. All data access occurs inside a transaction irrespective of whether the data is read or written. Do not use the auto-commit mode in applications. If any problems occurred during processing or rendering, an exception will be thrown and the database transaction rolled back.

protected void doGet(

HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{

SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" );

try {

// Begin unit of work

HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

// Process request and render page...

// End unit of work

HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();

}

catch (Exception ex) {

}

Open Session In View Pattern

The problem

A common issue in a typical (web-)application is the rendering of the view, after the main logic of the action has been completed, and therefore, the Hibernate Session has already been closed and the database transaction has ended. If you access detached objects that have been loaded in the Session inside your JSP (or any other view rendering mechanism), you might hit an unloaded collection or a proxy that isn't initialized. The exception you get is: LazyInitializationException: Session has been closed (or a very similar message). Of course, this is to be expected, after all you already ended your unit of work.

Solution

The solution, in two-tiered systems, with the action execution, data access through the Session, and the rendering of the view all in the same virtual machine, is to keep the Session open until the view has been rendered. In a three-tier environment the view might be rendered on the presentation virtual machine, not on the service virtual machine with the business and data access layer. Therefore, keeping the Session and transaction open is not an option. In this case you have to send the right "amount" of data to the presentation layer, so a view can be constructed with the Session already closed.

Another great explanation: http://springtips.blogspot.com/2007/07/open-session-in-view.html

How to:

  1. Implement a servlet Filter
  2. Use Spring

2. Spring:

http://cchweblog.wordpress.com/2009/10/10/using-opensessioninviewfilter-in-spring-web-application/

Web.xml


hibernateFilter

org.springframework.orm.hibernate3.support.OpenSessionInViewFilter




hibernateFilter
/*

This would take care of closing and opening session.

1. Using Filter

Web.xml

        HibernateFilter
        my.package.HibernateThreadFilter
    
 
    
        HibernateFilter
        /*
    

Servlet Filter Class

public class HibernateSessionRequestFilter implements Filter {
 
    private static Log log = LogFactory.getLog(HibernateSessionRequestFilter.class);
 
    private SessionFactory sf;
 
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {
 
        try {
            log.debug("Starting a database transaction");
            sf.getCurrentSession().beginTransaction();
 
            // Call the next filter (continue request processing)
            chain.doFilter(request, response);
 
            // Commit and cleanup
            log.debug("Committing the database transaction");
            sf.getCurrentSession().getTransaction().commit();

http://heapdump.wordpress.com/2010/04/04/should-i-use-open-session-in-view/

Miscellaneous

  1. sequence generation
  2. A org.hibernate.Session represents a single-threaded unit of work
  3. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once
  4. Keep hibernate.cfg.xml and log4j.properties file into the src/main/resources directory
  5. Switching the configuration option for this mechanism to "thread" allows the context of a current unit of work is bound to the current Java thread that executes the application. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the org.hibernate.Session from the thread and closes it for you
  6. Detached: The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process.

Thursday, March 17, 2011

Naming Conventions and Practices

Java naming conventions/good practices

  • is prefix should be used for boolean variables and methods. few alternatives: has, can and should
  • The term compute can be used in methods where something is computed.
    • valueSet.computeAverage(); matrix.computeInverse()
  • The term find can be used in methods where something is looked up.
    • vertex.findNearestVertex(); matrix.findSmallestElement();
  • The term initialize can be used where an object or a concept is established.
    • printer.initializeFontSet();
  • Plural form should be used on names representing a collection of objects.
    • Collection<Point> points;
  • Some key verbs
    • get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end
    • first/last, up/down, min/max, next/previous, old/new, open/close, show/hide, suspend/resume, etc.
  • Abbreviations in names should be avoided.
    • computeAverage(); // NOT: compAvg();

    • ActionEvent event; // NOT: ActionEvent e;
    • catch (Exception exception) { // NOT: catch (Exception e) {
  • Negated boolean variable names must be avoided.
    • bool isError; // NOT: isNoError

    • bool isFound; // NOT: isNotFound
  • Associated constants (final variables) should be prefixed by a common type name.
    • final int COLOR_RED = 1;
    • final int COLOR_GREEN = 2;
    • final int COLOR_BLUE = 3;
  • Exception classes should be suffixed with Exception.
    • class AccessException extends Exception.
  • Default interface implementations can be prefixed by Default.
    • class DefaultTableCellRenderer implements TableCellRenderer
  • Singleton classes should return their sole instance through method getInstance
  • File content must be kept within 80 columns.
  • Imported classes should always be listed explicitly.
    • import java.util.List; // NOT: import java.util.*;
  • . Class and Interface declarations should be organized in the following manner:
    • Class/Interface documentation.
    • class or interface statement.
    • Class (static) variables in the order public, protected, package (no access modifier), private.
    • Instance variables in the order public, protected, package (no access modifier), private.
    • Constructors.
    • Methods (no specific order).
  • Method modifiers should be given in the following order:
    • <access> static abstract synchronized <unusual> final native. The <access> modifier (if present) must be the first modifier.
  • Type conversions must always be done explicitly. Never rely on implicit type conversion.
    • floatValue = (int) intValue; // NOT: floatValue = intValue;
  • Array specifiers must be attached to the type not the variable.
    • int[] a = new int[20]; // NOT: int a[] = new int[20]
  • Class variables should never be declared public.
  • Variables should be kept alive for as short a time as possible.
  • Loop variables should be initialized immediately before the loop.
    • isDone = false; while (!isDone) {
  • The use of do-while loops can be avoided.
  • The use of break and continue in loops should be avoided.
    • These statements should only be used if they prove to give higher readability than their structured counterparts.
  • Reference: http://geosoft.no/development/javastyle.html

Tuesday, March 15, 2011

Basics Revisited Part 2..,

Constructors

  • constructor can't ever, ever, ever, have a return type
  • Constructors can't be marked static (they are after all associated with object instantiation), they can't be marked final or abstract (because they can't be overridden).
  • Can't use variable args on Constructor
    • Foo2(int... x, int t) { } // bad var-arg syntax

Variables

  • Primitives:
    • byte, short, int, long, float, double [8,16,32,64,32,64 bits respectively]
  • Reference Variables: Refers to an object
    • You can declare one or more reference variables,of the same type, in a single line.
    • String s1,s2,s3;
  • Instance Variables
    • Defined in class but outside methods.
    • Can be marked: final, transient
    • Cannot be marked: static(becomes class variable), synchronized, strictfp,abstract
  • Class variables
    • A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
  • Local Variables
    • Should be initialized
    • Live on stack
    • Exists only during the method scope.
    • Only final modifier applicable.
    • When you define a local variable same as instance variable it is called Shadowing.
  • Enums
    • Restricts a variable to predefined set of values.
    • enums can be declared as their own class, or enclosed in another class, and that the syntax for accessing an enum's members depends on where the enum was declared.
    • Cannot declare enums in methods.
    • An enum is a much safer and more flexible way to implement constants than was possible in earlier versions of Java.


 


 


 


 


 


 


Monday, March 7, 2011

Java Basics Revisited..,

  • Class: A template that describes state and behavior of a object
  • Object: new instance of a class.
  • State: The value assigned to an Objects instance variable
  • Behavior: methods in a class
  • Inheritance: allows code defined in one class to be reused in other classes
  • Interface: 100-percent abstract superclass that defines the methods a subclass must support
  • Every class should have a focused set of responsibilities.
  • Identifiers cannot start with a number!; You can't use a Java keyword as an identifier; No limit to number of characters an identifier can contain
  • Rules:
    • Classes: First letter capitalized, Should be a noun (Ex:- Account, Customer )
    • Interfaces: First letter capitalized, should be a adjective (Ex: -Runnable Serizlizable)
    • Methods
      The first letter should be lowercase, and then normal camelCase rules should be used. In addition, the names should typically be verb-noun pairs (getSize)
    • Variables
      Like methods, the camelCase format should be used, starting with a lowercase letter. Sun recommends short, meaningful names, which sounds good to us.

    • Constants
      Java constants are created by marking variables
      static and final. They should be named using uppercase letters with underscore characters as separators
    • Listeners: must start with either add/remove. Must end with Listener; Example: addActionListener, removeActionListener
    • There can be only one public class per source code file.
    • Files with no public classes can have a name that does not match any of the classes in the file
  • Access Control/Modifiers (Public, Private, Protected, Default) – code in one class can modify/access other class
    • Class:
      • Has only public and Default. Default means package level, only classes in that package can access it, other packages cant see this class.
      • Can use strictfp, abstract and final modifiers for a class. You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden.
    • Interfaces.
      • All interface methods are implicitly public and abstract
      • All variables defined in an interface must be public, static, and final—only constant, no instance variables
      • Interface methods must not be static. (int x=1 is implicitly public static final int x=1)
    • Method:
      • Has all four access levels.    
      • Default- package level access;
      • Protected – package + kids (who ever extends; If you try to access it using instance it will fail). The protected method becomes private to the classes in the package that the original class inherited.
      • Private: Class level; When a member is declared private, a subclass can't inherit it.
    • Variables
      • it's nearly always best to keep all variables private or protected.
      • Private/Protected/Default Access Control– same as method level.
      • Local variables: no access modifier except final.
  • Non-Access Modifiers
    • Final
      • Class: prevents the class from being subclassed. This is particularly useful, for example, when creating an immutable class like the String class.
      • Method: Prevents a method to be overridden. You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.
      • Method arguments: Variables passed to a method can have final modifier. which means it can't be modified within the method. In this case, "modified" means reassigning a new value to the variable. In other words, a final argument must keep the same value that the parameter had when it was passed into the method.
    • Abstract
      • Class: Classes which inherit a abstract class should implement the abstract methods
      • Methods: One method declared in a class as abstract makes the whole class abstract.
      • Variables: Abstract CANNOT be applied to variables.
    • Synchronized
      • Class: Not applicable
      • Method: Applicable and indicates that a method can be accessed by only one thread at a time.
      • Variables: Not Applicable
    • Native
      • Class: NA
      • Method: method is implemented in platform-dependent code. Note that a native method's body must be a semicolon (;) (like abstract methods), indicating that the implementation is omitted
      • Variables: NA
    • Strictfp
      • Class: Forces floating point to adhere to IEEE 754 standard. With strictfp, you can predict how your floating points will behave regardless of the underlying platform the JVM is running on.
      • Methods: same as class.
      • Variables: NA
    • Static
      • Concept: Doesn't depend on the state/instance of the class. Runs the same way independent of instance.
      • Class: NA (Unless they are nested)
      • Methods:
        • Exist before you make a new instance of the class.
        • static methods can't be overridden; they can only be re-defined.
        • Imagine you've got a utility class with a method that always runs the same way; its sole function is to return, say, a random number. It wouldn't matter which instance of the class performed the method—it would always behave exactly the same way. In other words, the method's behavior has no dependency on the state (instance variable values) of an object. So why, then, do you need an object when the method will never be instance-specific? Why not just ask the class itself to run the method?- that's what static does.
      • Variables:
        • all instances of a given class share the same value for any given static variable
        • Suppose you want to keep a running count of all instances instantiated from a particular class. Where do you actually keep that variable? It won't work to keep it as an instance variable within the class whose instances you're tracking, because the count will just be initialized back to a default value with each new instance. The answer to both the utility-method-always-runsthe-same scenario and the keep-a-running-total-of-instances scenario is to use the static modifier.

Friday, March 4, 2011

Setting up Clearcase plugin for Eclipse or STS

User Guide:
http://eclipse-ccase.sourceforge.net/documents/user_guide.pdf

Zip File:
http://sourceforge.net/projects/eclipse-ccase/files/

Usage:
http://sourceforge.net/apps/mediawiki/eclipse-ccase/index.php?title=Usage