Archive for January, 2011

Hibernate Annotations Named native Query


Problem: How to use named native queries in Hibernate/JPA Annotated Entities

Solution:

In the entity class, you can use these below annotations. Continuing with the earlier post, regarding the oracle connect sql, if chosen to

use the sql from an entity will look like below

@Entity
@SqlResultSetMapping(name = "implicit", entities = @EntityResult(entityClass = pakagepath.Employee.class))
@NamedNativeQuery(name = "namednativeqry", query = "select * from customer start with manager_id = :mgrId connect by prior emp_id = manager_id D relationship_cd = ‘IS MANAGER OF’", resultSetMapping = "implicit")

From the code, this can be called using the 

session.getNamedQuery("nativenamedqry").setString("mgrId",334);

,

Leave a comment

ORA-01436 CONNECT BY loop in user data


Problem:  When traversing a database table to find the hierachy of parent child (like manager, employee), this error happens

ORA-01436 CONNECT BY loop in user data

Solution:  If SQL Query looks like

select * from customer

start with manager_id = ‘334’

connect by prior emp_id = manager_id

above problem can happen, if the next record that is to be selected is a descendent of itself, which causes loop problem. By having another condition like below

 

select * from customer

start with manager_id = ‘334’

connect by prior emp_id = manager_id

AND relationship_cd = ‘IS MANAGER OF’

retrieves all the employees whose manager is either 334 and also those employees whose manager is children of manager 334

 

 

, ,

Leave a comment

Axis2 + Log4j


Problem: How to enable Log4j logging inside Axis2

Solution: When application is deployed as .aar (axis archive) file, even if log4j settings are done properly and logging is enabled, there are cases where log file is either not generated or logging is not happening.

This can be resolved by checking out the Axis2 source code from apache website (instead of checking out the axis2.war)  and replacing the log4j.properties file with the custom log4j.xml and log4j.dtd and then build the  axis2.war using maven

1. Check out the axis2 source code distribution

2. Navigate to src/main/webapp/WEB-INF/classes

3. Locate and replace log4j.properties with your log4j.xml and log4j.dtd

4. Inside log4j.xml , FileAppender shall  look like this

<appender name=”FileAppender”>

<param name=”File” value=”logs/newlog.log”/>

<!–Other Params goes here –>

</appender>

5.  Now build the axis2.war and package the app as war file (using maven or so) to deploy axis2 inside
application container as a webapp. When the application container is started, axis2.war is exploded to axis2
directory

6. Upon the application is accessed, newlog.log will be created and the generated logs can be viewed, provided log statements
are available and set to appropriate levels like Debug for debugging.

,

Leave a comment

Configuring Maven + Hibernate tools


Problem:  Database schema is available and need to generate hibernate configuration file, mapping files by reverse engineering. Use the generated hibernate mapping files to create POJO annotations and thereby use the annotated files for database persistence.

Solution:

This can be done using hibernate3-maven-plugin and using the goals as hbm2cfgxml,hbm2hbmxml and hbm2java  as shown below. As of now, i did this in two steps even though i am showing the entire pom here at one shot. (i.e comment execution for step2 while doing step1 and vice versa)

Step1: Generate the hibernate.cfg.xml and the mapping files.
Step2: Manally update the hibernate.cfg.xml with the <mapping resources=”path to above generated mapping.hbm.xml” /> files and then Generate the annotated classes

<build>
<plugins>

<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>hbm2cfgxml</id>
<phase>generate-resources</phase>
<goals>
<goal>hbm2cfgxml</goal>
</goals>
<inherited>false</inherited>
<configuration>
<components>
<component>
<name>hbm2cfgxml</name>
<implementation>annotationconfiguration</implementation>
<outputDirectory>target/classes</outputDirectory>
</component>
</components>
</configuration>
</execution>

<execution>
<id>hbm2hbmxml</id>
<phase>generate-resources</phase>
<goals>
<goal>hbm2hbmxml</goal>
</goals>
<inherited>false</inherited>
<configuration>
<components>
<component>
<name>hbm2hbmxml</name>
<outputDirectory>target/classes</outputDirectory>
</component>
</components>
<componentProperties>
<packagename>provide.your.package.name</packagename>
</componentProperties>
</configuration>
</execution>

<execution>
<id>hbm2java</id>
<phase>generate-sources</phase>
<goals>
<goal>hbm2java</goal>
</goals>
<inherited>false</inherited>
<configuration>
<components>
<component>
<name>hbm2java</name>
<implementation>annotationconfiguration</implementation>
</component>
</components>
<componentProperties>
<implementation>annotationconfiguration</implementation>
<jdk5>true</jdk5>
<ejb3>true</ejb3>
<format>true</format>
<export>false</false>
<configurationfile>target/classes/hibernate.cfg.xml</configurationfile>
</componentProperties>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
……………………
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
Step 1 is fairly straightforward. To perform step 1, run the below command

mvn generate-resources

which  will generate configuration file (hbm2cfxml goal) in target/classes and hibernate mappings (hbm2hbmxml goal) in target/classes as well. Now you need to COPY them to your src/main/resources (in eclipse for example) and update the hibernate.cfg.xml with
the <mapping resources=”path to all the above generated mapping.hbm.xml” /> files

I faced issues while generating annotated classes in Step 2, key thing to generate annotated classes, with ejb3 annotations for entity classes (like @Entity, @Id etc) is to set the flag <ejb3>true<ejb3> and also provide <jdk5>true</jdk5> to turn on generics. Now comment step1 executions in pom.xml and  run the below command

mvn generate-sources

which will generate annotated classes by default at target\hibernate3\generated-sources. You can copy them over to your source and use them with the DAO’s for java persistence

,

Leave a comment

Mapping List Object in Hibernate


Below self explanatory sample application helps to understand how to persist a list object using Hibernate as persistence layer and MySQL as database.

—————————————————————————————————

package project2;

import java.util.ArrayList;

import org.hibernate.Session;
import org.hibernate.Transaction;

import project2.persistence.HibernateUtil;
public class MappingListDemo {

public static void main(String[] args) {

Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

try {
customers cust1 = new customers(“Dave”);

ArrayList list1 = new ArrayList();
list1.add(new custorders(“SOA Using Java Web Services”));
list1.add(new custorders(“Java Persistence with Hibernate”));
cust1.setOrders(list1);
session.save(cust1);

customers cust2 = new customers(“Jim”);
ArrayList list2 = new ArrayList();
list2.add(new custorders(“Java Unleashed”));
list2.add(new custorders(“Design Patterns”));
cust2.setOrders(list2);
session.save(cust2);

tx.commit();

session.flush();
session.close();
} catch (Exception he)

{
System.out.println(“Exception caught: ” + he);
}
}

}

————————————————————————————————–

————————————————————————————————–

package project2;
public class custorders {
String orderinfo;

int id;
public custorders() {
}
public custorders(String d) {
orderinfo = d;
}
public int getId() {
return id;
}

public void setId(int s) {
id = s;
}
public void setOrderinfo(String orderinfo) {
this.orderinfo = orderinfo;
}

public String getOrderinfo() {
return orderinfo;
}
}

————————————————————————————————–

—————————————————————————————————

package project2;
import java.util.List;

public class customers {
String name;
List orders;
int id;

public customers() {
}

public customers(String d) {
name = d;
}
public String getName() {
return name;
}

public void setName(String a) {
name = a;
}
public int getId() {
return id;
}

public void setId(int s) {
id = s;
}
public void setOrders(List orders) {
this.orders = orders;
}

public List getOrders() {
return orders;
}
}

————————————————————————————————–

—————————————————————————————————

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>

<hibernate-mapping>

<class name=”project2.customers”   table=”customer”>
<id name=”id” >

<generator/>

</id>

<property name=”name” />

<list name=”orders” cascade=”all”>

<key column=”item_id” />
<list-index column=”position” />
<one-to-many />

</list>

</class>

</hibernate-mapping>

————————————————————————————————–

—————————————————————————————————

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>

<hibernate-mapping>

<class name=”project2.custorders”   table=”custorder”>
<id name=”id”>

<generator/>

</id>

<property name=”orderinfo”  />

</class>

</hibernate-mapping>

————————————————————————————————–

—————————————————————————————————
<!DOCTYPE hibernate-configuration SYSTEM
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd“>
<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/hibernatetest</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”></property>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<!– Use the C3P0 connection pool provider –>
<property name=”hibernate.c3p0.min_size”>5</property>
<property name=”hibernate.c3p0.max_size”>20</property>
<property name=”hibernate.c3p0.timeout”>300</property>
<property name=”hibernate.c3p0.max_statements”>50</property>
<property name=”hibernate.c3p0.idle_test_period”>3000</property>
<!– Show and print nice SQL on stdout –>
<property name=”show_sql”>true</property>
<property name=”format_sql”>true</property>
<!– List of XML mapping files –>

<mapping/>
<mapping/>

<mapping resource=”project2/custorders.hbm.xml”/>
<mapping resource=”project2/customers.hbm.xml”/>
</session-factory>
</hibernate-configuration>

—————————————————————————————————

MySQL query tables used in above examples…

create table custorder(id int not null primary key auto_increment,
orderinfo text,position int,item_id int);

create table customer
( id int not null primary key auto_increment, name VARCHAR(40));

,

Leave a comment

Restricting multiple sessions in IE7


This blog helps you by providing some thoughts on how to manage HTTP session and restrict multiple users logging into your web application using IE 7 browser tab features. Let me brief little bit about the background of the problem and few possible solutions.

Lets assume your web application is currently able to restrict same user logging in multiple times from a particular machine using IE 6 like browser. This means that if user1 has logged in IE6 browser 1, then user1 will not be able to login in IE6 browser2. In this scenario, browser1 HTTP session is different from browser2 session and we will be easily able to restrict the user1.

Our goal is to restrict the user1 logging in multiple times in browser like IE 7 which provides tab features (multiple tabs in same browser). IE7 Browser shares the same session across tabs and this would be our key to restrict user as follows.

Step1: Get all active sessions from your singleton class

MySingleton  mysin= MySingleton.getSessions();   which returns hashmap of all your current sessions. userid is the key and the session as the value.

Step2: loop through all your sessions and compare the current session with the list.

Enumeration e1 = sing.keys();

while (e1.hasMoreElements())

{

String enumUser = (String) e1.nextElement();

HttpSession enumSess = (HttpSession)sing.get(enumUser );

if(enumSess == session)

{

//Matching session found which means that another user is alreading using this browser to your web application

//Keep count of sessions

count++;

session.setAttribute(”mycount”,count);

}

//somewhere down the line, your logic to block the user if count>1

,

1 Comment