Latest Entries

Logging with logback and external configuration

Logs and logging in general is the number one friend of a developer when it comes to troubleshooting in a live environment. Changing logging level on the fly is very handy in situations that something has gone wrong. In this post we will configure logback in order to have different log level per environment and also to be able to change it on the fly without the need of re-deployments or restart neither our app or our application server.

We will use a .properties file that will define the current environment and the path of an external logback.xml that will have the configuration which will be used only for the production environment. All these will be used by the traditional in-app logback.xml.

In order to succeed this we will use three features of logback. The Automatically reloading configuration file upon modification the File inclusion and the Conditional processing of configuration files.

Be aware that for those three features to work combined, we will need to have at least the 0.9.28 logback version and also to include Janino library in our application, otherwise our setup will fail to work.

In order to achieve the aforementioned behavior we will create a main logback.xml, a logback-dev.xml, a logback-prod.xml and a logback.properties file. The latter, will contain the information regarding the environment that will affect the logging configuration per environment. It is proposed to put the logback.properties file inside our server’s classpath so that it can be independent from our application(s). The logback.xml, that will be inside our deployable, will fetch this information and based on that it will use either the logback-dev.xml or the logback-prod.xml. Now in order to be able to edit the logback-prod.xml whenever we want, we will put it somewhere outside our deployable and inside our server. The logback-dev.xml could be inside our deployable, we don’t really care about that since it will be only accessed in development environments. The logback.properties file will also contain the root path were we can find the logback-prod.xml.

So taking into consideration all the above, here are the files we need:

logback.properties

mode=prod
logRoot=/opt/Oracle/Weblogic/user_projects/domains/myApp_domain

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Document   : logback.xml
    Created on : October 3, 2012, 10:18 AM
    Author     : leonidas patouchas
-->
<configuration scan="true" scanPeriod="300 seconds">
	<property resource="logback.properties" />

	<if condition='property("mode").equals("prod")'>
		<then>
			<include file="${logRoot}/myApp/logback-prod.xml" />
		</then>
	</if>
	<if condition='property("mode").equals("dev")'>
		<then>
			<include resource="logback-dev.xml" />
		</then>
	</if>
</configuration>

logback-dev.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Document   : logback-dev.xml
    Created on : October 3, 2012, 10:18 AM
    Author     : leonidas patouchas
    Description:
        Purpose of the document follows.
-->
<configuration>
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d %p [%c] - &lt;%m&gt;%n</Pattern>
        </layout>
    </appender>
    <!--Daily rolling file appender -->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
          <File>${MYAPP_HOME}/nyApp.log</File>
          <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
          <FileNamePattern>gr-myApp.%d{yyyy-MM-dd}.log</FileNamePattern>
          <MaxHistory>2</MaxHistory>
          </rollingPolicy>
          <layout class="ch.qos.logback.classic.PatternLayout">
          <Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</Pattern>
          </layout>
    </appender> 

    <logger name="org.springframework" level="INFO"/>
    <logger name="org.apache.openjpa" level="DEBUG"/>
    <logger name="gr" level="TRACE"/>

    <root level="TRACE">
        <appender-ref ref="stdout"/>
        <appender-ref ref="file" />
    </root>
</configuration>

logback-prod.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
    Document   : logback-prod.xml
    Created on : October 3, 2012, 10:18 AM
    Author     : leonidas patouchas
    Description:
        Purpose of the document follows.
-->
<configuration>
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d %p [%c] - &lt;%m&gt;%n</Pattern>
        </layout>
    </appender>
    <!--Daily rolling file appender -->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
          <File>${MYAPP_HOME}/nyApp.log</File>
          <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
          <FileNamePattern>gr-myApp.%d{yyyy-MM-dd}.log</FileNamePattern>
          <MaxHistory>2</MaxHistory>
          </rollingPolicy>
          <layout class="ch.qos.logback.classic.PatternLayout">
          <Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</Pattern>
          </layout>
    </appender> 

    <logger name="org.springframework" level="INFO"/>
    <logger name="org.apache.openjpa" level="DEBUG"/>
    <logger name="gr" level="ERROR"/>

    <root level="ERROR">
        <appender-ref ref="stdout"/>
        <appender-ref ref="file" />
    </root>
</configuration>

Note that the difference between the dev and the prod logback is only the loglevel. Of course we could do any kinds of changes to the configuration and have totally different logs per environment. In our case, the logback is pre-configured to check for updates in the logging configuration every 300 seconds. Be aware of performance issues if you decrease the refresh time to a few seconds.

Hibernate Mapping with Annotations

In the previous post we used the .hbm.xml to map our POJO with the DB table. There is another way we can do that, that does not involve any .xml file. Everything will be done in our POJO, so no extra files needed. That kind of implementation requires at least Java 5, hibernate 3.2.0 core and above and it is based on Annotations. We will use annotations to map our POJO.

The Persons.java class we used in the previous example (and was automatically generated by NetBeans) looked like this:

package gr.persons.entities;

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

public class Person  implements java.io.Serializable {

     private BigDecimal id;
     private String name;
     private String surname;
     private Date birthdate;
     private String sex;

    public Person() {
    }

    public Person(BigDecimal id) {
        this.id = id;
    }
    public Person(BigDecimal id, String name, String surname, Date birthdate, String sex) {
       this.id = id;
       this.name = name;
       this.surname = surname;
       this.birthdate = birthdate;
       this.sex = sex;
    }

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

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

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

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

    public String getSurname() {
        return this.surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Date getBirthdate() {
        return this.birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }

    public String getSex() {
        return this.sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

}

And we mapped id through the Persons.hbm.xml.

For the annotated solution we will have to alter a little bit the Persons.java:

package gr.persons.entities;

import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "PERSON", schema = "YOUR_SCHEMA")
public class Person implements java.io.Serializable {

    @Id
    @Column(name = "ID", unique = true, nullable = false)
    private BigDecimal id;

    @Column(name = "NAME", length = 50)
    private String name;

    @Column(name = "SURNAME", length = 50)
    private String surname;

    @Temporal(TemporalType.DATE)
    @Column(name = "BIRTHDATE", length = 7)
    private Date birthdate;

    @Column(name = "SEX", length =10)
    private String sex;

    public Person() {
    }

    public Person(BigDecimal id) {
        this.id = id;
    }

    public Person(BigDecimal id, String name, String surname, Date birthdate, String sex) {
        this.id = id;
        this.name = name;
        this.surname = surname;
        this.birthdate = birthdate;
        this.sex = sex;
    }

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

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

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

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

    public String getSurname() {
        return this.surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Date getBirthdate() {
        return this.birthdate;
    }

    public void setBirthdate(Date birthdate) {
        this.birthdate = birthdate;
    }

    public String getSex() {
        return this.sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

The implementation is pretty straight forward. With the annotation @Entity we defined that the Persons.java is an entity that represents the persistent object. With @Table we defined that the our Persons.java class is mapped with the table PERSONS in the schema YOUR_SCHEMA. We also defined the Primary Key that is the id using the @Id annotation. Finally we used the @Column annotation to map our DB columns.

Now in order for our changes to work we have to change our hibernate.cfg.xml. Instead of mapping the resource of Person.hbm.xml we will now map the class Persons.java:

Before:

<mapping resource="gr/persons/entities/Person.hbm.xml"/>

After:

<mapping class="gr.persons.entities.Person"/>

An other thing we must note is that in our HibernateUtil.java class we create our Session Factory based on AnnotationConfiguration.

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

This is needed for annotations to work. If we use Configuration, it will not work.

P.S Special thanks to SaperDuper that motivated me to write the annotated version of the previous tutorial :)

Hibernate – DAO – Java Tutorial

This tutorial will show how to use Database Access Objects using Hibernate in your java application.

To begin with we should create a table with a primary key. For this example we will create a table named Person with columns: ID, NAME, SURNAME, BIRTHDATE, SEX.We will use as PK the ID filed.

We will create a new java project named Persons in NetBeans and add in libraries the appropriate library according to the DB that we will use. In my case, that I use an oracle DB it is the ojdbc driver. Also change the main package to gr.persons

  • Hibernate Configuration

NetBeans is really helpful when it comes to generating the hibernate configuration file and also the entities from the DB. Select your project and go to New – Hibernate – Hibernate Configuration Wizard. After you select your select your DB connection yourhibernate.cfg.xml will be generated. Open the generated file and add this line under the last property:

[...]
    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

Your hibernate.cfg.xml should now look like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@171.0.0.0:1522:SID</property>
    <property name="hibernate.connection.username">YOUR_SCHEMA</property>
    <property name="hibernate.connection.password">YOUR_SCHEMA</property>
    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>
  </session-factory>
</hibernate-configuration>

* note here that YOUR_SCHEMA and the hibernate.connection.url will be according to your DB connection.

By the way, leave your hibernate.cfg.xml in the default package. It’s not the best practice, but for now leave it there.

Now in order to generate our POJO and map it with the DB we should first create a reveng.xml file. Again select your project and choose New – Hibernate – Hibernate Reverse Engineering Wizard. The wizard will connect to the DB based on the configurations in the hibernate.cfg.xml and it will prompt you to choose the wanted table(s). In our case we will choose the table Person.
*Note here, that if a table does not have a PK then we will not be able to generate the pojos and map it.

Now we are ready to generate our POJO and its mapping. Once again, select your project and go to New – Hibernate – Hibernate Mapping Files and POJOs from Database. Put them in a package gr.persons.entities.

Now in that package you will see a Person.java and also a Person.hbm.xml file. You have your object and it’s mapping accordingly. Moreover, if you go to hibernate.cfg.xml you will see that now it has also a mapping resource that points to the Person.hbm.xml file (line 12):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@171.0.0.0:1522:SID</property>
    <property name="hibernate.connection.username">YOUR_SCHEMA</property>
    <property name="hibernate.connection.password">YOUR_SCHEMA</property>
    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>
    <mapping resource="gr/persons/entities/Person.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

By the above steps we have configured Hibernate and we have finished with the configurations for our connection and mapping with the DB.

Hibernate is using SessionFactory to manage Sessions. These objects are quite heavy when it comes to resources and we have to be careful on how we use them in our application. That is why we will create a very common class, the HibernateUtil class that will manage our session. We can create a HibernateUtil class from NetBeans directly but we will create our own which will contain some more goodies.

HibernateUtil class

package gr.persons.utils;

import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
*
* @author leonidas
*/
public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public static Session beginTransaction() {
Session hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}

public static void commitTransaction() {
HibernateUtil.getSession().getTransaction().commit();
}

public static void rollbackTransaction() {
HibernateUtil.getSession().getTransaction().rollback();
}

public static void closeSession() {
HibernateUtil.getSession().close();
}

public static Session getSession() {
Session hibernateSession = sessionFactory.getCurrentSession();
return hibernateSession;
}
}

As you can see from the HibernateUtil class, we have the Session, opening, committing and rolling back a transaction. We will use numerous times this methods in our application.

Now we are ready to use hibernate.

  • Database Access Objects (DAO)

It is not necessery to create DAO’s (Database Access Objects) in order to use hibernate from now on. However, it is better to seperate the implementation of the persisten framwork and the database layer from the rest of our application. It makes our application more flexible and better stuctured.

A good practice is to create a generic DAO that will be used from all of our specific DAO’s since some operations are common among all DAO’s. Our generic DAO will implement methods like save, merge, delete, findAll, findByID, findMany and findOne.

GenericDAO interface

package gr.persons.dao;

/**
 *
 * @author leonidas
 */
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import org.hibernate.Query;

public interface GenericDAO<T, ID extends Serializable> {

    public void save(T entity);

    public void merge(T entity);

    public void delete(T entity);

    public List<T> findMany(Query query);

    public T findOne(Query query);

    public List findAll(Class clazz);

    public T findByID(Class clazz, BigDecimal id);
}

GenericDAOImpl abstract class

package gr.persons.dao;

import gr.persons.utils.HibernateUtil;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author leonidas
 */
public abstract class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {

    protected Session getSession() {
        return HibernateUtil.getSession();
    }

    public void save(T entity) {
        Session hibernateSession = this.getSession();
        hibernateSession.saveOrUpdate(entity);
    }

    public void merge(T entity) {
        Session hibernateSession = this.getSession();
        hibernateSession.merge(entity);
    }

    public void delete(T entity) {
        Session hibernateSession = this.getSession();
        hibernateSession.delete(entity);
    }

    public List<T> findMany(Query query) {
        List<T> t;
        t = (List<T>) query.list();
        return t;
    }

    public T findOne(Query query) {
        T t;
        t = (T) query.uniqueResult();
        return t;
    }

    public T findByID(Class clazz, BigDecimal id) {
        Session hibernateSession = this.getSession();
        T t = null;
        t = (T) hibernateSession.get(clazz, id);
        return t;
    }

    public List findAll(Class clazz) {
        Session hibernateSession = this.getSession();
        List T = null;
        Query query = hibernateSession.createQuery("from " + clazz.getName());
        T = query.list();
        return T;
    }
}

In our application we have only the Person class, so we will create the interface PersonDAO that will extend the GenericDAO and the class PersonDAOImpl that will extend the GenericDAOImpl and implement the PersonDAO. This is a common practice. For each and every DAO that we will create we will follow the same steps.

PersonDAO inteface

package gr.persons.dao;

import gr.persons.entities.Person;
import java.math.BigDecimal;

/**
 *
 * @author leonidas
 */
public interface PersonDAO extends GenericDAO<Person, BigDecimal> {
}

PersonDAOImpl class

package gr.persons.dao;

import gr.persons.entities.Person;
import gr.persons.utils.HibernateUtil;
import java.math.BigDecimal;
import org.hibernate.Query;

/**
 *
 * @author leonidas
 */
public class PersonDAOImpl extends GenericDAOImpl<Person, BigDecimal> implements PersonDAO {
}

In a way, someone could say that we are now ready. We can call the ProductDAO and start loading, saving objects e.t.c
For example:

PersonDAO personDAO = new PersonDAOImpl();
[...]
personDAO.findByID(null, BigDecimal.valueOf(1));
[...]
personDAO.save(person);
[...]
personDAO.findAll(Person.class);
[...]
personDAO.findOne(query);

Well… yes, this is functional of course but we are almost there!

First of all, we might want to find a person by its name and surname. This can be done by using the GenericDAO’s findOne(query) method. We could write in our program:

[...]
Person person = null;
String name = "John";
String surname = "Doe";
String sql = "SELECT p FROM Person p WHERE p.name = :name AND p.surname = :surname";
HibernateUtil.beginTransaction();
Query query = HibernateUtil.getSession().createQuery(sql).setParameter("name", name).setParameter("surname", surname);
person = findOne(query);
HibernateUtil.commitTransaction();
[...]

*Note that in the highlighted lines, we used the HibernateUtil to begin our transaction and also to commit our transaction.

This will do the job but it is better to create a segmentation in our code. Why not implement it inside our PersonDAO? This is what we will do, this is why we created the DAO’s at the fist place. We will change the PersonDAO and PersonDAOImpl like this:

PersonDAO

package gr.persons.dao;

import gr.persons.entities.Person;
import java.math.BigDecimal;

/**
 *
 * @author leonidas
 */
public interface PersonDAO extends GenericDAO<Person, BigDecimal> {

    public Person findByName(String name, String surname);
}

PersonDAOImpl

package gr.persons.dao;

import gr.persons.entities.Person;
import gr.persons.utils.HibernateUtil;
import java.math.BigDecimal;
import org.hibernate.Query;

/**
 *
 * @author leonidas
 */
public class PersonDAOImpl extends GenericDAOImpl<Person, BigDecimal> implements PersonDAO {

    public Person findByName(String name, String surname) {
        Person person = null;
        String sql = "SELECT p FROM Person p WHERE p.name = :name AND p.surname = :surname";
        Query query = HibernateUtil.getSession().createQuery(sql).setParameter("name", name).setParameter("surname", surname);
        person = findOne(query);
        return person;
    }
}

Now PersonDAO except the methods that inherits from GenericDAO it is also providing the findByName method.

We are now one step before finishing with the DAO design. Actually, we finished with the DAO design, we will no just use them.

Now we will create the classes that will manage our programs business logic. As you have noticed, our DAO’s do not have any transactions inside. That is crucial. We should never add transactions to our DAO’s since we should leave that logic outside of them. Let’s say for example that we might want to deal as one transaction the deletion of one object the update of an other one and the query for a third one. If we had transactions inside the save, delete and find methods of our DAO’s then we could not accomplish that.

That is why we will create a class that will manage our business logic and will talk with our DAO’s when it needs to interact with the DB. We will call them managers, PersonManager.class. PersonManager will implement our business logic and when they need to interact with the persistence it will call the PersonDAO. In our case, the PersonManager will not implement elaborate business, just the basics.

PersonManager interface

package gr.persons.session;

import gr.persons.entities.Person;
import java.math.BigDecimal;
import java.util.List;

/**
 *
 * @author leonidas
 */
public interface PersonManager {

    public Person findByPersonName(String name, String surname);

    public List<Person> loadAllPersons();

    public void saveNewPerson(Person person);

    public Person findPersonById(BigDecimal id);

    public void deletePerson(Person person);
}

PersonManagerImpl class

package gr.persons.session;

import gr.persons.dao.PersonDAOImpl;
import gr.persons.entities.Person;
import gr.persons.utils.HibernateUtil;
import gr.persons.dao.PersonDAO;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NonUniqueResultException;
import org.hibernate.HibernateException;

/**
 *
 * @author leonidas
 */
public class PersonManagerImpl implements PersonManager {

    private PersonDAO personDAO = new PersonDAOImpl();

    public Person findByPersonName(String name, String surname) {
        Person person = null;
        try {
            HibernateUtil.beginTransaction();
            person = personDAO.findByName(name, surname);
            HibernateUtil.commitTransaction();
        } catch (NonUniqueResultException ex) {
            System.out.println("Handle your error here");
            System.out.println("Query returned more than one results.");
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
        }
        return person;
    }

    public List<Person> loadAllPersons() {
        List<Person> allPersons = new ArrayList<Person>();
        try {
            HibernateUtil.beginTransaction();
            allPersons = personDAO.findAll(Person.class);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
        }
        return allPersons;
    }

    public void saveNewPerson(Person person) {
        try {
            HibernateUtil.beginTransaction();
            personDAO.save(person);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
            HibernateUtil.rollbackTransaction();
        }
    }

    public Person findPersonById(BigDecimal id) {
        Person person = null;
        try {
            HibernateUtil.beginTransaction();
            person = (Person) personDAO.findByID(Person.class, id);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
        }
        return person;
    }

    public void deletePerson(Person person) {
        try {
            HibernateUtil.beginTransaction();
            personDAO.delete(person);
            HibernateUtil.commitTransaction();
        } catch (HibernateException ex) {
            System.out.println("Handle your error here");
            HibernateUtil.rollbackTransaction();
        }
    }
}

This was it. We are now 100% ready to continue with the rest of our application.

To sum up, we have our generic DAO’s that implement methods that are common among all DAO’s. We have our specific DAO’s that are extending the generic DAO’s and also adding their own methods and finally we have the managers that enclose the business logic of our application.

Now, we can call from our main class the manager and execute whatever we want:

PersonManager personManager = new PersonManagerImpl();

Person wanted = personManager.findByPersonName("Steven", "Seagal");

Person chuck = new Person(BigDecimal.valueOf(5), "Chuck", "Norris",new Date(), "Male");

personManager.saveNewPerson(chuck);

List allPersons = personManager.loadAllPersons();

You can find the full NetBeans project here. Note that you will have to change the schema in the hibernate.reveng.xml (match-schema=”BSCS_TEST”), Person.hbm.xml (schema=”YOUR_SCHEMA”). Also, you should change the hibernate.cfg.xml according to your DB connection.

P.S The ID of the Person is type of BigDecimal. This is due to oracle’s Number variable. In your example it my be, int or long or whatever!

EDIT:
If you want to map your POJO with annotations and not the .hbm.xml file take a look at this post.

New Year, new toys

2011 came with two new toys for me.

First, a new lens for my precious Nikon D80. The Nikon 24mm f/2.8. I wanted for a while now a wide prime lens. They are ideal for street and indoors photography and their small size make them extremely portable. I was between the Nikon 28mm f/2.8 and the one I finally bought. The reviews for the latter were excellent (in contrast to the ones about the 28mm) and I managed to find it refurbished in a I-have-to-buy-this-now price. I haven’t tested it properly yet, so I can’t really provide any kind of feedback regarding its quality. I like the feeling of a prime lens though. They drive you towards more creative paths and make you think your frame a little bit more before you shoot. I love my Nikon 50mm f/1.8 also but it is too narrow for anything else than portraits in my humble opinion (especially for a DX camera). One more thing that is a plus for prime lenses is that they produce better quality photos than any zoom lens at their specific focal length (of course we are talking about lenses in the same quality / price category). Ideally, in the future I will acquire a zoom 70-300mm or a prime 105mm lens (i haven’t decide yet) to complete my lens arsenal!

Secondly, an exceptional Belkin Bluetooth Music Receiver! I didn’t even imagine that there were gadgets like this one out there! With this thing you can connect your iPhone with your speakers, home cinema system e.t.c through bluetooth and play your music wireless! Given the fact that I have all the music I would like to hear in my iPhone it is great to be able to hear on the fly my library through my sound system in the living room! A perfect gift, thanks guys!

Ιστοριες ΙΚΑ V.1

Κλεινεις ραντεβού στο Ι.Κ.Α 40 μέρες μετα το αρχικό τηλεφώνημα στο κεντρο και αισθάνεσαι ευτυχισμένος. Φτάνει η μέρα που έχεις το ραντεβού και αφού συμβουλευτεις τον κατάλογο με τις απεργιακές κινητοποιήσεις της ημέρας και αισθανθεις σαν να επιασες 6αρι στο Λοττο αφού τυχαίνει να μην απεργούν οι γιατροί σήμερα πας τρισευτυχισμενος στον γιατρό!

-Καλησπερα, ενα χαρτί για κολυμβητήριο θα ήθελα.

-Α, δεν βγάζουμε εδώ τέτοια, πρέπει να πατε στα δημοτικά ιατρεία, πρωινές ώρες.

Τι έγινε ρε παιδιά;

Αναρωτιέμαι με το 16% του μισθού μας τι ιδιωτική ιατρική περίθαλψη θα είχαμε;

Υ.Γ πρώτο post από το wordpress iPhone app. So an so….

SendtoDropbox

Dropbox is a great service and Dropbox iPhone app is a cool but inadequate application. The reason behind its inadequacy is Apple’s restrictions for all Applestore apps. All apps are sandboxed and can not use the iOS’s file system and its contents. Thus, from your dropbox iPhone app you can only upload photos or videos. One more lucking feature of dropbox app is that you can not edit any of your files. If you have a jailbroken iPhone through you can easily edit your stuff with iFile but there is no option for uploading them to your dropbox. That’s kind of crappy if you ask me.

To overcome this issue we can use the sendtodropbox service. Sendtodropbox creates a unique email address that pushes all the mails that receive to your dropbox. So you can simply email whatever file you want (through iFile) and in a few minutes it will be in your dropbox. By default the files are saved to Attachments / filename but it also has  some (limited) options you can choose from.

I am using it a couple of days now and it “just works”. That’s enough for me!

Passwords Security and LastPass

To remember usernames and passwords for the online services we use can be an extremely tedious procedure. What most people do (among them also me) is to have at least three passwords that start from the strongest, followed by the ok but not that safe one and finish with the “123456” one. We tend to put our strong one to the most important websites like our email, facebook, online bank accounts and we distribute the other two among sites, forums, services that we do not use that often. Well, to start with, this is totally wrong. By doing this if someone finds out our main password then it has access to the most important piece of our online life.

Having in mind that, most of us create multiple alternatives of our strong password based on a simple algorithm that can easily be remembered. So far so good. Having multiple passwords for our most important services and on top of that two more passwords for the less important, we can sleep safe at nights.

What happens though, when we decide to change passwords? Continue reading…

Think before you login. Firesheep.

While I was preparing a post about secure passwords and password management systems I run into this:

Well, we all knew it is possible, we all knew it is not that difficult but seeing it in action it is socking, to say the least! I installed it and tested it and of course it does what it says. So from now on think twice what sites you are going to visit through an open Wi-Fi!

Firesheep

via

Shredder Widget

Every now and then we all want to delete once and for all some private files. Solutions for permanent deleting files are a lot. If you are not in Interpol or FBI’s black lists then just deleting files by sending them to the trash and empty it, is what you are used to do. This will prevent (non-geeks) people to lay their eyes on your files. But if you could be a little bit more safe and do it with style why not give it a try?! Shredder Widget does that for you! With three safety levels your dashboard widget promises you stylish and permanent* file deletions!

*I wouldn’t put my money on that, it sure adds extra protection though.

iOS4 and Battery Problems

iPhone 3Gs owners have been caught to be complaining about battery drain issues after they upgraded their precious iPhone’s to iOS4. I don’t blame them because after a week or so with Apple’s new operating system I might say that a slight problem indeed occurs but through a few steps it could be easily alleviated.

To begin with, Apple’s “pioneer and innovating” multitasking system (multitasking that’s not actually multitasking but it’s something like a pseudo-multitasking trying to impersonate multitasking) is indeed a great upgrade and I sure love to download totally legal stuff from Installous while I am listening to streaming radio and browsing to the web but that kind of usage isn’t battery friendly at all. Especially, if you tend to neglect closing applications that you were using previously and do not need anymore. I thought that iOS4 would be a little bit smarter and close some inactive apps after a while but it seems that it doesn’t!

So, what are the steps we need to follow to prevent us from the perpetual quest of feeding our iPhone’s with energy?

The answer is to Jailbreak you iPhone and download sbsettings. By this mean you can monitor fast and with ease whichever applications are actually running at any time (cos iOS4 multitasking bar is showing both running and previously opened apps and that’s kind of confusing and not helpful at all). From sbsettings you can turn off any apps that are running and you do
not want to use them any more. Some apps that are opened while you are doing something else are in ‘freeze’ mode. That means that iOS4 had saved its state and will restore it when you reopen them while in the meantime the are inactive. You might think that that is ok and since the app is inactive it might not affect your battery.
Well guess what? You are wrong, cos iOS4 in order to “freeze” any app it has to use some of your limited RAM to store stuff. More RAM in use more battery needed and so on (well apparently this is a false statement!). Also, use the very handy “Free Up Memory” from sbsettings that does a great job!

One more thing I have noticed is that iOS4 more often drains battery faster than it should even if you have closed all the apps (phone and mail stay always on btw). I enjoy the goodies of iOS4 combined with jailbreak from the first day it sat on my iPhone so I don’t have non-jailbrake experience of the iOS4. Thus, I can’t really tell if this problem is iOS4’s or is caused byJailbreak. What I do know is that the solution is quite simple. If you notice that kind of behavior then just respring (from sbsettings again) your iPhone and in the 99% of the times the problem will be solved. If not, then just reboot.

To sum up, just try to close any app you exit when there is no reason for that app to operate under multitasking. Moreover, look every now an then sbsettings’ processes tab for any unwanted running apps and also try to respring it once or twice per day. Finally, free some memory through sbsettings. That does the job for me and I am pretty sure it will do it for you to.



Copyright © 2010. Leonidas Patouchas. All rights reserved.

RSS Feed. This blog is proudly powered by Wordpress and uses Modern Clix, a theme by Rodrigo Galindez.