google Analytics

Thursday, July 29, 2010

JBOSS AOP Example

/**
* @@org.jboss.aspects.security.SecurityDomain ("other")
*/
public class Calculator {

/**
* @@org.jboss.aspects.security.Unchecked
*/
public Calculator () { }

/**
* @@org.jboss.aspects.security.Permissions ({"Authorized"})
* @@org.jboss.jbossaop.aspect.TrialLimit
*/
public double getPayment (int principal, double rate,
int term) {
rate = rate / 100.;
rate = rate / 12.;
double tmp = Math.pow(1.+rate, term);
return (principal * tmp * rate) / (tmp - 1.);
}


}
public class CalculatorServlet extends HttpServlet {

private Calculator cal = null;

public void init () throws ServletException {
cal = new Calculator ();
}

public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

response.setContentType("text/html");

ServletOutputStream out = response.getOutputStream();

String para = null;
int principal = 200000;
double rate = 8.0;
int term = 360;
double payment = 0.;

para = request.getParameter("principal");
if (para != null && para.length() > 0) {
principal = Integer.parseInt(para);
}

para = request.getParameter("rate");
if (para != null && para.length() > 0) {
rate = Double.parseDouble(para);
}

para = request.getParameter("term");
if (para != null && para.length() > 0) {
term = Integer.parseInt(para);
}

try {
payment = cal.getPayment(principal, rate, term);

out.println("<html>");
out.println("<head><title>Mortgage Calculator</title></head>");

out.println("<body>");
out.println("<h1>Mortgage Calculator</h1>");

out.println("<form action=\"Calculator\" method=\"get\">");
out.println("Principal (dollar):");
out.println("<input type=\"text\" name=\"principal\" value=\"");
out.print(principal);
out.println("\">");
out.println("<br/>");

out.println("Interest rate (annual percentage point):");
out.println("<input type=\"text\" name=\"rate\" value=\"");
out.print(rate);
out.println("\">");
out.println("<br/>");

out.println("Term (months):");
out.println("<input type=\"text\" name=\"term\" value=\"");
out.print(term);
out.println("\">");
out.println("<br/>");

out.println("<input type=\"submit\">");
out.println("</form>");

out.println("<p>The monthly payment is");
out.println("<b>");
out.print(payment);
out.println("</b>");
out.println("dollars</p>");

out.println("</body>");
out.println("</html>");
} catch (Throwable e) {
out.println("<html>");
out.println("<head><title>Error</title></head>");

out.println("<body>");
out.println("<h1>Error</h1>");
out.println("<p>Maybe you hit the access limit ");
out.println("or do not have sufficient permission");
out.println("<br>");
out.println("<p>The error message is:");
out.println("<pre>");
out.println(e.getMessage());
out.println("</pre>");
out.println("</body>");
out.println("</html>");
}
}
}


public interface TrialLimit {
}

public class TrialLimitAspect {

private static int count = 0;

public Object checkLimit (Invocation invocation)
throws Throwable {
System.out.println("Check whether the trial limit is reached");
count++;
if (count < 5) {
return invocation.invokeNext();
} else {
throw new Exception("Hit the maximum access count");
}
}
}
--jboss-aop.xml
<aop>
<aspect class="org.jboss.jbossaop.aspect.TrialLimitAspect"
scope="PER_VM"/>

<bind pointcut="execution(* *->@org.jboss.jbossaop.aspect.TrialLimit(..))">
<advice name="checkLimit"
aspect="org.jboss.jbossaop.aspect.TrialLimitAspect"/>
</bind>
</aop>

Wednesday, July 28, 2010

Ejb3 Stateful Bean Example

--jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost

@Stateful
@Remote(ShoppingCart.class)
public class ShoppingCartBean implements ShoppingCart, Serializable
{
private HashMap cart = new HashMap();

public void buy(String product, int quantity)
{
if (cart.containsKey(product))
{
int currq = cart.get(product);
currq += quantity;
cart.put(product, currq);
}
else
{
cart.put(product, quantity);
}
}

public HashMap getCartContents()
{
return cart;
}

@Remove
public void checkout()
{
System.out.println("To be implemented");
}
}



import java.util.HashMap;
import javax.ejb.Remove;

public interface ShoppingCart
{
void buy(String product, int quantity);

HashMap getCartContents();

@Remove void checkout();
}


public class Client
{
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
ShoppingCart cart = (ShoppingCart) ctx.lookup("ShoppingCartBean/remote");

System.out.println("Buying 1 memory stick");
cart.buy("Memory stick", 1);
System.out.println("Buying another memory stick");
cart.buy("Memory stick", 1);

System.out.println("Buying a laptop");
cart.buy("Laptop", 1);

System.out.println("Print cart:");
HashMap fullCart = cart.getCartContents();
for (String product : fullCart.keySet())
{
System.out.println(fullCart.get(product) + " " + product);
}

System.out.println("Checkout");
cart.checkout();

System.out.println("Should throw an object not found exception by invoking on cart after @Remove method");
try
{
cart.getCartContents();
}
catch (javax.ejb.NoSuchEJBException e)
{
System.out.println("Successfully caught no such object exception.");
}


}
}

EJB3 Stateless Bean Example

A stateful session bean automatically saves bean state between client invocations
without your having to write any additional code,Amazon. In contrast,
stateless session beans do not maintain any state and model application services
that can be completed in a single client invocation. You could build stateless
session beans for implementing business processes such as charging a credit card
or checking customer credit history

for example

import javax.ejb.Stateless;

@Stateless
public class CalculatorBean implements CalculatorRemote, CalculatorLocal
{
public int add(int x, int y)
{
return x + y;
}

public int subtract(int x, int y)
{
return x - y;
}
}


@Local
public interface CalculatorLocal extends Calculator
{
}

@Remote
public interface CalculatorRemote extends Calculator
{

}


public interface Calculator
{
int add(int x, int y);

int subtract(int x, int y);
}


public class Client
{
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
Calculator calculator = (Calculator) ctx.lookup("CalculatorBean/remote");

System.out.println("1 + 1 = " + calculator.add(1, 1));
System.out.println("1 - 1 = " + calculator.subtract(1, 1));
}
}

Monday, July 26, 2010

Hibernate List execute Associatons SQL

select column selection from different POJO

public void executeAssociationObjectsHQL(Session session)
{
String hql = "from Product p inner join p.supplier as s";
Query query = session.createQuery(hql);
List results = query.list();
displayObjectsList(results);
}


public void displayObjectsList(List list)
{
Iterator iter = list.iterator();
if (!iter.hasNext())
{
System.out.println("No objects to display.");
return;
}
while (iter.hasNext())
{
System.out.println("New object");
Object[] obj = (Object[]) iter.next();
for (int i=0;i {
System.out.println(obj[i]);
}


}
}

public void displayObjectList(List list)
{
Iterator iter = list.iterator();
if (!iter.hasNext())
{
System.out.println("No objects to display.");
return;
}
while (iter.hasNext())
{
Object obj = iter.next();
System.out.println(obj.getClass().getName());
System.out.println(obj);
}
}

HIbernate Filter Example

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="com.hibernatebook.filters.User">
    <id name="id" type="int">
      <generator class="native"/>
    </id>
    <property name="username" type="string" length="32"/>
    <property name="activated" type="boolean"/>
    <filter name="activatedFilter" condition=":activatedParam = activated"/>
  </class>
  <filter-def name="activatedFilter">
    <filter-param name="activatedParam" type="boolean"/>
  </filter-def>
</hibernate-mapping>


public class SimpleFilterExample
{
public static void main (String args[])
{
Session session = HibernateHelper.getSession();

//insert the users
insertUser("ray",true,session);
insertUser("jason",true,session);
insertUser("beth",false,session);
insertUser("judy",false,session);
insertUser("rob",false,session);

//Show all users
System.out.println("===ALL USERS===");
displayUsers(session);

//Show activated users
Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
System.out.println("===ACTIVATED USERS===");
displayUsers(session);

//Show non-activated users
filter.setParameter("activatedParam",new Boolean(false));
System.out.println("===NON-ACTIVATED USERS===");
displayUsers(session);

session.close();
}

public static void displayUsers(Session session)
{
Transaction trans = session.beginTransaction();
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext())
{
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
if (user.isActivated())
{
System.out.println("activated.");
}
else
{
System.out.println("not activated.");
}
}
trans.commit();
}
public static void insertUser(String name, boolean activated, Session session)
{
Transaction trans = session.beginTransaction();
User user = new User();
user.setUsername(name);
user.setActivated(activated);
session.save(user);
trans.commit();
}
}

Sunday, July 25, 2010

Spring Autowiring Demo byName:byType:constructor:autodetect

=============================================================

=============================================================

public class AutowiringDemo {

public static void main(String[] args) {
XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("/META-INF/spring/autowiringdemo1-context.xml"));

autowire(bf, "byName");
autowire(bf, "byType");
autowire(bf, "constructor");
autowire(bf, "autodetect");
}

private static void autowire(BeanFactory factory, String beanName) {
System.out.println(beanName + ":");
System.out.println(factory.getBean(beanName));
System.out.println();
}
}

=============================================================

=============================================================

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="foo" class="com.apress.prospring2.ch03.autowiring.Foo"/>
    <bean id="bar" class="com.apress.prospring2.ch03.autowiring.Bar"/>

    <bean id="byName" autowire="byName" class="com.apress.prospring2.ch03.autowiring.Target"/>
    <bean id="byType" autowire="byType" class="com.apress.prospring2.ch03.autowiring.Target"/>
    <bean id="constructor" autowire="constructor" class="com.apress.prospring2.ch03.autowiring.Target"/>
    <bean id="autodetect" autowire="autodetect" class="com.apress.prospring2.ch03.autowiring.Target"/>
</beans>


=============================================================

=============================================================
public class Bar {

@Override
public String toString() {
return getClass().getName();
}
}

public class Target {
private Foo foo;
private Foo foo2;
private Bar bar;

public Target() {
System.out.println("Target()");
}

public Target(Foo foo) {
System.out.println("Target(Foo)");
this.foo = foo;
}

public Target(Foo foo, Bar bar) {
System.out.println("Target(Foo, Bar)");
this.foo = foo;
this.bar = bar;
}

public void setDependency(Bar bar) {
System.out.println("Target.setDependency(Bar)");
this.bar = bar;
}

public void setFoo(Foo foo) {
System.out.println("Target.setFoo(Foo)");
this.foo = foo;
}

public void setFoo2(Foo foo2) {
System.out.println("Target.setFoo2(Foo)");
this.foo2 = foo2;
}

public void setBar(Bar bar) {
System.out.println("Target.setBar(Bar)");
this.bar = bar;
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Target");
sb.append("{foo=").append(foo);
sb.append(", foo2=").append(foo2);
sb.append(", bar=").append(bar);
sb.append('}');
return sb.toString();
}
}

=============================================================

=============================================================

public class Foo {

@Override
public String toString() {
return getClass().getName();
}
}

=============================================================

=============================================================

Friday, July 23, 2010

Hibernate Named Query Example

hibernate-mapping
query name="smc.Product.findProductTypeByName">from Producttype type where type.name=? order by type.name ASCSELECT t.value FROM TEXT t, POSTPAIDOPTIONGROUP g where t.textualdescription=g.name AND t.language = 0 AND t.media = 0 AND t.client = 0 AND t.touchpoint = 0 AND t.role = 0 order by t.value ASC sql-query


--Code Snippet
Query queryObject = null;
queryObject = getDBSession().getNamedQuery("Product.findProductTypeByName");
queryObject.setParameter(0, name);
List productTypeList = queryObject.list();




--code Sbippet
List groupName=getDBSession(userdto).getNamedQuery("Product.getGroupName").list();

HiberNate Named Query Example


from Producttype type where type.name=? order by type.name ASC
SELECT t.value FROM TEXT t, POSTPAIDOPTIONGROUP g where t.textualdescription=g.name AND t.language = 0 AND t.media = 0 AND t.client = 0 AND t.touchpoint = 0 AND t.role = 0 order by t.value ASC

Spring File Upload Download full Example with Oracle Database

create table FILES
(
ID NUMBER(10) not null,
FILENAME VARCHAR2(100) not null,
NOTES VARCHAR2(100),
TYPE VARCHAR2(40),
FILES BLOB
);
public class Files {
private int id;
private String filename;
private String notes;
private String type;
private byte[] file;
public int getId() {
return id;
}
.......
}
public class FilesService extends JdbcDaoSupport {
String query = null;
public Files find(int id) {
query = "select * from files where id = ?";
try {
Files file = (Files) getJdbcTemplate().queryForObject(query, new Object[] {id},
new RowMapper() {
Files fl;
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
fl = new Files();
fl.setId(rs.getInt(1));
fl.setFilename(rs.getString(2));
fl.setNotes(rs.getString(3));
fl.setType(rs.getString(4));
fl.setFile(rs.getBytes(5));
return fl;
}
});

return file;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public List listAll() {
query = "select id, filename, notes, type from files";

try{
List files = getJdbcTemplate().query(query, new BeanPropertyRowMapper(Files.class));\
return files;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void save(final Files file) {
query = "insert into files (filename, notes, type, file) values (?, ?, ?, ?)";
try {
synchronized(this) {
getJdbcTemplate().update(new PreparedStatementCreator() {

public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, file.getFilename());
statement.setString(2, file.getNotes());
statement.setString(3, file.getType());
statement.setBytes(4, file.getFile());
return statement;
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void delete(int id) {
query = "delete from files where id = ?";

try {
getJdbcTemplate().update(query, new Object[] {id});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public class FilesForm extends AbstractController {
private FilesService filesService;

public void setFilesService(FilesService filesService) {
this.filesService = filesService;
}

protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {

List files = this.filesService.listAll();

return new ModelAndView("files", "files", files);
}
}
public class FilesController extends MultiActionController {
private FilesService filesService;

public void setFilesService(FilesService filesService) {
this.filesService = filesService;
}
public ModelAndView upload(HttpServletRequest request,
HttpServletResponse response) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartRequest.getFile("file");
Files file = new Files();
file.setFilename(multipartFile.getOriginalFilename());
file.setNotes(ServletRequestUtils.getStringParameter(request, "notes"));
file.setType(multipartFile.getContentType());
file.setFile(multipartFile.getBytes());
this.filesService.save(file);
return new ModelAndView("redirect:files.htm");
}
public ModelAndView download(HttpServletRequest request,
HttpServletResponse response) throws Exception {
int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
Files file = this.filesService.find(id);
response.setContentType(file.getType());
response.setContentLength(file.getFile().length);
response.setHeader("Content-Disposition","attachment; filename=\"" + file.getFilename() +"\"");
FileCopyUtils.copy(file.getFile(), response.getOutputStream());
return null;
}
public ModelAndView delete(HttpServletRequest request,
HttpServletResponse response) throws Exception {
int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
this.filesService.delete(id);
return new ModelAndView("redirect:files.htm");
}

}



(&?xml version="1.0" encoding="UTF-8"?(&
(&beans xmlns="http://www.springframework.org/schema/beans"
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.xsd"(&

(&!-- datasource --(&
(&bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"(&
(&property name="driverClassName" value="com.mysql.jdbc.Driver" /(&
(&property name="username" value="root"(&(&/property(&
(&property name="password" value="root"(&(&/property(&
(&property name="url" value="jdbc:mysql://localhost:3306/test"(&
(&/property(&
(&/bean(&
(&!-- template --(&
(&bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"(&
(&property name="dataSource" ref="dataSource" /(&
(&/bean(&
(&!-- services --(&
(&bean id="filesService" class="com.spring.example.service.FilesService"(&
(&property name="jdbcTemplate" ref="jdbcTemplate"/(&
(&/bean(&
(&/beans(&

(&?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"(&

(&!-- mapping --(&
(&bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"(&
(&property name="mappings"(&
(&props(&
(∝ key="files.htm"(&filesForm(&/prop(&
(∝ key="upload.htm"(&filesController(&/prop(&
(∝ key="download.htm"(&filesController(&/prop(&
(∝ key="delete.htm"(&filesController(&/prop(&
(&/props(&
(&/property(&
(&/bean(&

(&!-- The view resolver --(&
(&bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" /(&

(&bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"(&
(&property name="maxUploadSize" value="5242880" /(&
(&/bean(&

(&!-- controller --(&
(&bean id="filesForm" class="com.spring.example.web.FilesForm"(&
(&property name="filesService" ref="filesService"/(&
(&/bean(&

(&bean id="filesController" class="com.spring.example.web.FilesController"(&
(&property name="filesService" ref="filesService"/(&
(&property name="methodNameResolver"(&
(&bean class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver"(&
(&property name="mappings"(&
(&props(&
(∝ key="/upload.htm"(&upload(&/prop(&
(∝ key="/download.htm"(&download(&/prop(&
(∝ key="/delete.htm"(&delete(&/prop(&
(&/props(&
(&/property(&
(&/bean(&
(&/property(&
(&/bean(&
(&/beans(&

Thursday, July 15, 2010

Jboss Management Interface Example

import javax.interceptor.Interceptors;
import org.jboss.ejb3.annotation.Clustered;
import org.jboss.ejb3.annotation.Depends;
import org.jboss.ejb3.annotation.Management;
import org.jboss.ejb3.annotation.Service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;

/**
* @author Anish
*
*/
@Service (name = "AnishService")
@Management (PlcService.class)
@Clustered
@Depends ({"jboss.ha:service=HASingletonDeployer,type=Barrier"})
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class AnishServiceBean implements AnishService{

private CISLogger logger = new CISLogger(getClass().getName());

@Override
public void create() throws Exception {
logger.info("Anish service created");
}

@Override
public void destroy() {
logger.info("Anish service destroyed");
}

@Override
public void start() throws Exception {
logger.info("Anish Cluster Wide Singleton Started");

/*
* deploys all spring beans.
* setting the application context will let other projects to use these beans.
*/


ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
AnishConstants.SPRING_CONTEXT_PATH);

ApplicationContext AnishContext = (ApplicationContext) applicationContext
.getBean(AnishConstants.Anish_CONTEXT_BEAN_NAME);

for(String name : AnishContext.getBeanDefinitionNames())
logger.debug(name + " spring bean loaded");

AnishApplicationManager applicationManager = (AnishApplicationManager) AnishContext
.getBean("AnishApplicationManager");


}

@Override
public void stop() {
logger.info("Anish Cluster Wide Singleton Stoped");
}

}

public interface AnishService {

void create() throws Exception;
void start() throws Exception;
void stop();
void destroy();
}

Wednesday, July 14, 2010

loading a properties file Currently Being Moderated PropertiesFromDeploymentFile

PropertiesFromDeploymentFile


Here is some sample code for loading a properties file in the META-INF directory of a deployment file.

public Properties getPropAsResource(String name) throws Exception

{

InputStream is = getClass().getResourceAsStream("/META-INF/" + name);

if (is == null)

{

throw new Exception("Unable to locate resource: " + name);

}

Properties confProp = new Properties();

confProp.load(is);

return confProp;

}}}


Thursday, July 8, 2010

Hibernate Pagination Example

---- Anish Pagination Support contact anish2good@yahoo.co.in

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class HibernateResultDao extends HibernateDaoSupport implements ResultDao {

public ResultSearchResult search(final ResultSearchArgument a) {
return (ResultSearchResult) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query;
ResultSearchResult result = new ResultSearchResult();
query = session.createQuery("from Result where name = :s");
query.setString("s", a.getS());
query.setFirstResult(a.getFirstResult());
query.setMaxResults(a.getMaxResults());
result.setResult(query.list());

query = session.createQuery("select count(*) from Result where name = :s");
query.setString("s", a.getS());
result.setTotalResults((Long)query.uniqueResult());

return result;
}
});
}


hibernate pagination query
spring hibernate pagination
hibernate paging query
hibernate scrollable

Hibernate one to Many Example

Hibernate one Many Example

hibernate one-to-many



=============================================================
 

=============================================================

<?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">
<!--
    Anish
-->
<hibernate-mapping>
    <class name="session.Student" table="STUDENT" schema="RUBY">
        <id name="id" type="java.lang.Long">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="10" />
        </property>
        <set name="subjects" inverse="true">
            <key>
                <column name="EMPID" precision="22" scale="0" />
            </key>
            <one-to-many class="session.Subject" />
        </set>
    </class>
</hibernate-mapping>



<?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">
<!--
    ANish
-->
<hibernate-mapping>
    <class name="session.Subject" table="SUBJECT" schema="RUBY">
        <id name="id" type="java.lang.Long">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <many-to-one cascade="save-update" name="student" class="session.Student" fetch="select">
            <column name="EMPID" precision="22" scale="0" />
        </many-to-one>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="10" />
        </property>
    </class>
</hibernate-mapping>

 

 
related
Relation One to Many  Hibernate  Java
hibernate one-to-many
hibernate one-to-many list
hibernate one-to-many set
hibernate one-to-many example
hibernate one-to-many cascade
hibernate one-to-many annotation
hibernate one-to-one
hibernate many-to-many
hibernate many to one cascade
ANish



public class Student implements java.io.Serializable {

// Fields

private Long id;
private String name;
private Set subjects = new HashSet(0);

// Constructors

/** default constructor */
public Student() {
}

/** minimal constructor */
public Student(Long id) {
this.id = id;
}

/** full constructor */
public Student(Long id, String name, Set subjects) {
this.id = id;
this.name = name;
this.subjects = subjects;
}

// Property accessors

public Long getId() {
return this.id;
}

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

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public Set getSubjects() {
return this.subjects;
}

public void setSubjects(Set subjects) {
this.subjects = subjects;
}

}


public class Subject implements java.io.Serializable {

// Fields

private Long id;
private Student student;
private String name;

// Constructors

/** default constructor */
public Subject() {
}

/** minimal constructor */
public Subject(Long id) {
this.id = id;
}

/** full constructor */
public Subject(Long id, Student student, String name) {
this.id = id;
this.student = student;
this.name = name;
}

// Property accessors

public Long getId() {
return this.id;
}

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

public Student getStudent() {
return this.student;
}

public void setStudent(Student student) {
this.student = student;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}



}

Hibernate EmptyInterceptor Example

/**
* @author NathA1
*/
public class EntryInterceptor extends EmptyInterceptor {
/*
* @see org.hibernate.EmptyInterceptor#onSave(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
*/
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
final Date now = new Date();
final String loginUserName ="NathA1";
setValue(state, propertyNames, "datecreation", now);
setValue(state, propertyNames, "usercreation", loginUserName);
setValue(state, propertyNames, "dateupd", now);
setValue(state, propertyNames, "userupd", loginUserName);
return true;
}

/*
* @see org.hibernate.EmptyInterceptor#onFlushDirty(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
*/
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
final Date now = new Date();
final String loginUserName ="NathA1";
setValue(currentState, propertyNames, "dateupd", now);
setValue(currentState, propertyNames, "userupd", loginUserName);
return true;
}

/**
* Sets the value.
*
* @param currentState the current state
* @param propertyNames the property names
* @param propertyToSet the property to set
* @param value the value
*/
private void setValue(Object[] currentState, String[] propertyNames, String propertyToSet, Object value) {
for (int i = 0; i < propertyNames.length; i++) {
if (propertyNames[i].equalsIgnoreCase(propertyToSet)) {
currentState[i] = value;
}
}
}

}

Message Driven Bean 3.0

Message Driven Bean(MDB) 3.0 Exampe:--

import javax.ejb.MessageDriven;

import javax.ejb.ActivationConfigProperty;

import javax.jms.Message;

import javax.jms.MessageListener;

/**

*

* @author NathA1

*

*/

@MessageDriven(activationConfig =

{

@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),

@ActivationConfigProperty(propertyName="destination", propertyValue="queue/anish"),

@ActivationConfigProperty(propertyName ="acknowledgeMode",propertyValue = "Auto-acknowledge"),

@ActivationConfigProperty(propertyName ="subscriptionDurability",propertyValue = "NonDurable"),

@ActivationConfigProperty(propertyName = "messageSelector",propertyValue = "Priority = ‘HIGH'"),

@ActivationConfigProperty(propertyName = "minSession",propertyValue = "1"),

@ActivationConfigProperty(propertyName = "maxSession",propertyValue = "15"),

@ActivationConfigProperty(propertyName = "maxMessages",propertyValue = "1")

})

public class MyMdb implements MessageListener {

@Override

public void onMessage(Message arg0) {

// TODO Auto-generated method stub

}

}

Running Jboss in Cluster Commands

TITLE node 1 (8080)

rem cd /../-5.1.0.GA/bin


cd bin

run -c node1 -g CISDocsPartition -u 239.255.100.100 -b localhost -Djboss.messaging.ServerPeerID=1 -Djboss.service.binding.set=ports-01

pause


TITLE node 2 (8080)

rem cd jboss-5.1.0.GA/bin

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_04

cd bin

run -c node2 -g CISDocsPartition -u 239.255.100.100 -b localhost -Djboss.messaging.ServerPeerID=1 -Djboss.service.binding.set=ports-02

paus

JBOSS Tree chache Service Examples































Hibernate versioning Example

The <version> element is optional and indicates that the table contains versioned data. This is
particularly useful if you plan to use long transactions.

<version
column="version_column"
name="propertyName"
type="typename"
access="field|property|ClassName"
unsaved-value="null|negative|undefined"
generated="never|always"
insert="true|false"
node="element-name|@attribute-name|element/@attribute|."
/>

Version numbers can be of Hibernate type long, integer, short, timestamp or calendar.
A version or timestamp property should never be null for a detached instance. Hibernate will detect
any instance with a null version or timestamp as transient, irrespective of what other unsavedvalue
strategies are specified. Declaring a nullable version or timestamp property is an easy way
to avoid problems with transitive reattachment in Hibernate. It is especially useful for people using
assigned identifiers or composite key

<?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="session.Writer" table="WRITER" schema="SMC">
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="increment" />
</id>
<version name="version" type="java.lang.Long">
<column name="VERSION" precision="22" scale="0" />
</version>
<property name="name" type="java.lang.String">
<column name="NAME" length="20" />
</property>
</class>
</hibernate-mapping>

=============================================================

=============================================================

public class Writer implements java.io.Serializable {

// Fields

private Long id;
private Long version;
private String name;

// Constructors

/** default constructor */
public Writer() {
}

/** full constructor */
public Writer(String name) {
this.name = name;
}

// Property accessors

public Long getId() {
return this.id;
}

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

public Long getVersion() {
return this.version;
}

public void setVersion(Long version) {
this.version = version;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

}


=============================================================

=============================================================
Hibernate Automatic Versioning
How to do optimistic locking in Spring
Optimistic Locking and Versioning in Hibernate
StaleObjectState Excption

Wednesday, July 7, 2010

Hibernate OnceperRequestFilter Example

OncePerRequestFilter Example:--

public class HibernateSessionFilter extends OncePerRequestFilter {

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Session session = null;
try {
SessionFactory sf = lookupSessionFactory(request);
session = sf.openSession(new DateEntryInterceptor());
}
private SessionFactory lookupSessionFactory(HttpServletRequest request) {
SessionFactory sf = null;
sf = (SessionFactory) getContext(request).getBean("stagingSessionFactory");
return sf;
}
public ApplicationContext getContext(HttpServletRequest httpRequest) {
return WebApplicationContextUtils.getRequiredWebApplicationContext(httpRequest.getSession().getServletContext());
}

}

Spring Hibernate Property Place Holder Configurator

Spring Hibernate Property Place Holder Configurator



/WEB-INF/classes/hibernate.properties




-- hibernate.properties file
database1=staging,staging
staging.driverClassName=oracle.jdbc.driver.OracleDriver
staging.url=jdbc:oracle:thin:@localhost:1521:XE
staging.username=smc
staging.password=smc
staging.maxActive=100
staging.maxIdle=30
staging.maxWait=1000
staging.defaultAutoCommit=false
staging.database1=192.63.222.135,Staging
staging.hibernate.show_sql=true
staging.hibernate.dialect=org.hibernate.dialect.Oracle9Dialect
staging.hibernate.default_schema=test
staging.hibernate.connection.autocommit=false

Spring- Hibernate Configuration iin Application Context


${staging.driverClassName}
${staging.url}
${staging.username}
${staging.password}
${staging.maxActive}
${staging.maxIdle}
${staging.maxWait}
${staging.defaultAutoCommit}






${staging.database1}
${staging.hibernate.show_sql}
${staging.hibernate.dialect}
${staging.hibernate.default_schema}
${staging.hibernate.connection.autocommit}





classpath:/database/



Spring-Hibernate

Hibernate Criteria Examples:--

public void executeEqualsCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.eq("name","Mouse"));
List results = crit.list();
displayProductsList(results);
}

public void executeNotEqualsCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.ne("name","Mouse"));
List results = crit.list();
displayProductsList(results);
}

public void executeLikePatternCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.like("name","Mou%"));
List results = crit.list();
displayProductsList(results);
}

public void executeILikeMatchModeCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.ilike("name","browser", MatchMode.END));
List results = crit.list();
displayProductsList(results);
}

public void executeNullCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.isNull("name"));
List results = crit.list();
displayProductsList(results);
}

public void executeGreaterThanCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.gt("price",new Double(25.0)));
List results = crit.list();
displayProductsList(results);
}

public void executeAndCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.gt("price",new Double(25.0)));
crit.add(Restrictions.like("name","K%"));
List results = crit.list();
displayProductsList(results);
}

public void executeOrCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Criterion name = Restrictions.like("name","Mou%");
LogicalExpression orExp = Restrictions.or(price,name);
crit.add(orExp);
List results = crit.list();
displayProductsList(results);
}

public void executeAndOrCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Criterion name = Restrictions.like("name","Mou%");
LogicalExpression orExp = Restrictions.or(price,name);
crit.add(orExp);
crit.add(Restrictions.ilike("description","blocks%"));
List results = crit.list();
displayProductsList(results);
}

public void executeDisjunctionCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Criterion name = Restrictions.like("name","Mou%");
Criterion desc = Restrictions.ilike("description","blocks%");
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(price);
disjunction.add(name);
disjunction.add(desc);
crit.add(disjunction);
List results = crit.list();
displayProductsList(results);
}

public void executeSQLCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.sqlRestriction("{alias}.name like 'Mou%'"));
List results = crit.list();
displayProductsList(results);
}

public void executePagingCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.setFirstResult(1);
crit.setMaxResults(2);
List results = crit.list();
displayProductsList(results);
}

public void executeUniqueResultCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
crit.setMaxResults(1);
Product product = (Product) crit.uniqueResult();
//test for null here if needed

List results = new ArrayList();
results.add(product);
displayProductsList(results);
}

public void executeUniqueResultExceptionCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
Criterion price = Restrictions.gt("price",new Double(25.0));
Product product = (Product) crit.uniqueResult();
//test for null here if needed

List results = new ArrayList();
results.add(product);
displayProductsList(results);
}

public void executeOrderCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.gt("price",new Double(25.0)));
crit.addOrder(Order.desc("price"));
List results = crit.list();
displayProductsList(results);
}


public void executeOneToManyAssociationsCriteria(Session session)
{
Criteria crit = session.createCriteria(Supplier.class);
Criteria prdCrit = crit.createCriteria("products");
prdCrit.add(Restrictions.gt("price",new Double(25.0)));
List results = crit.list();
displaySupplierList(results);
}

public void executeAssociationsSortingCriteria(Session session)
{
Criteria crit = session.createCriteria(Supplier.class);
crit.addOrder(Order.desc("name"));
Criteria prdCrit = crit.createCriteria("products");
prdCrit.add(Restrictions.gt("price",new Double(25.0)));
//prdCrit.addOrder(Order.desc("price"));
List results = prdCrit.list();
displaySupplierList(results);
}

public void executeManyToOneAssociationsCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
Criteria suppCrit = crit.createCriteria("supplier");
suppCrit.add(Restrictions.eq("name","MegaInc"));
List results = crit.list();

displayProductsList(results);
}

public void executeQBECriteria(Session session)
{
Criteria crit = session.createCriteria(Supplier.class);
Supplier supplier = new Supplier();
supplier.setName("MegaInc");
crit.add(Example.create(supplier));
List results = crit.list();

displaySupplierList(results);
}

public void executeNotNullOrZeroQBECriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
Product exampleProduct = new Product();
exampleProduct.setName("Mouse");
Example example = Example.create(exampleProduct);
example.excludeZeroes();
crit.add(example);
List results = crit.list();

displayProductsList(results);
}


public void executeQBEAdvancedCriteria(Session session)
{
Criteria prdCrit = session.createCriteria(Product.class);
Product product = new Product();
product.setName("M%");
Example prdExample = Example.create(product);
prdExample.excludeProperty("price");
prdExample.enableLike();
Criteria suppCrit = prdCrit.createCriteria("supplier");
Supplier supplier = new Supplier();
supplier.setName("SuperCorp");
suppCrit.add(Example.create(supplier));
prdCrit.add(prdExample);
List results = prdCrit.list();

displayProductsList(results);
}

public void executeRowCountCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.setProjection(Projections.rowCount());
List results = crit.list();
displayObjectList(results);
}

public void executeAggregatesCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.max("price"));
projList.add(Projections.min("price"));
projList.add(Projections.avg("price"));
projList.add(Projections.countDistinct("description"));
crit.setProjection(projList);
List results = crit.list();
displayObjectsList(results);
}

public void executeProjectionCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("name"));
projList.add(Projections.property("description"));
crit.setProjection(projList);
List results = crit.list();
displayObjectsList(results);
}

public void executeGroupByCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.groupProperty("name"));
projList.add(Projections.property("price"));
crit.setProjection(projList);
List results = crit.list();
displayObjectsList(results);
}

public void executeDistinctCriteria(Session session)
{
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.gt("price",new Double(25.0)));
crit.add(Restrictions.like("name","K%"));
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List results = crit.list();
displayProductsList(results);
}