Tag Archives: jpa

jpa nativeQueries

Sometimes JPQL just isnt enough… JPQL is rendered differently then expected, ie nested selects dont work… so native SQL queries need to be done…

main problem is the return value. It is possible to define SqlResultSetMappings, but these where kinda confusing. had problems with primary keys… so without these structures, a typeless list of object-array is returned:

   final List result = entityManager.createNativeQuery(“SELECT a, b FROM table”).getResultList(); 

for each row an Object[] is put into the list.The Array contains Objects of a and b.

logging eclipselink

the big downside of JPA is in my opinion the JPQL… normaly it is pretty, pretty,pretty good… when only doing simple stuff. As soon as it get complex, where i first try it in SQL and then rewrite it in JPQL it gets bad… as long as no error has occured, it didnt output the from-JPQL-rendered-SQL… and i actually tried to debug it, tried to access it in java… but didnt tried to change the config…

<property name=”eclipselink.logging.level.sql” value=”FINE” />
<property name=”eclipselink.logging.parameters” value=”true” />

these two lines enable the logging of SQL… … bah…

SQL having

I needed to select an object-id of a row where a value reached a max value. Kinda confusing, so example:

SELECT id, MAX(value) FROM table
GROUP BY id

simple… and now i needed to check, if the value is bigger then something… lets say 5:

SELECT id FROM (
       SELECT id, MAX(value) AS bigValue FROM table
       GROUP BY id)
WHERE bigValue > 5

and yes. A join would be fine too… but actually i needed this query in JPA. and JPQL can’t handle nested selects… so a different solution was needed: HAVING! having is a select on a group…

SELECT id FROM table
GROUP BY id
HAVING MAX(value) > 5

cool 🙂 JPA didnt handle the HAVING… 🙁

jpa type safe entityManager calls

testing our jpa daos always worked successful… but i think this was mainly, because we filled during test the data on the database and got the data and tested it in the same transaction. therefore the data might be still stored in cache and never an actuall db call was made… this needs to be analysed and tested in near future… but thats a different blog entry… hopefully…

this blog entry is about the problem, which occures, when the db actuall is called 🙂

We have a GenericDao and all find all calls worked… and we have object based daos… following example, with an random object… lets take Person:

    public List<Person> getPersonByName(final String name) {
        @SuppressWarnings(“unchecked”)
        final List<Person> list = (List<Person>) entityManager
                .createNamedQuery(Person.GET_PERSON_BY_NAME)
                .setParameter(“name”, name)
                .getResultList();
        return list;
    }

This resulted in an exception… dont have the Exception here, but was something with an Object[] missmatch… and something about an non initialitzed EntityManager… the problem was the @SuppressWarnings(“unchecked”): or the warrning, which we just ignored… getResultList() returns a List… and casting List to List<Person> just doesnt work… whats the solution? Simple… just tell the named query, that kind of type it is… so it returns an List<Person> instead of the List…

 .createNamedQuery(Person.GET_PERSON_BY_NAME, Person.class)

and the @SuppressWarnings(“unchecked”) isnt used anymore 🙂

timestamp with jpa

so i have my jpa project with some really nice DAOs and i was really happy… all unit tests are up and running and everything looked good… but it wasnt…

i store timestamp(6) in the oracle db and the mapping class looks good and correct:

@Column(name = “TIME_ADDED”)
@Temporal(TemporalType.DATE)
private Date timeAdded;

the @Temporal defines the mapping type… and actual DATE is really only the date… TIMESTAMP is the thing i wanted…

The @Temporal annotation denotes, whether annotated property should be mapped to java.sql.Date (holds only date part), java.sql.Time (holds only time part) or to java.sql.Timestamp (holds date and time also with fractions of second). It has nothing to do with generation of property value.
(http://stackoverflow.com/questions/2591570/hibernate-reverse-engineering-procedure-generated-temporaltemporaltype-timestam)

and btw. unit tests will not find these errors… due to jpa caching… 🙁

weaving: spring and eclipselink

What is weaving?

Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime. (http://static.springsource.org/spring/docs/2.5.x/reference/aop.html)

So weaving is used to load objects and manipulate them… so… why? and why did this concern me?

ok in my project we use spring with eclipselink and the idea was to create the entities in spring and just @Autowire them for usage…  but it needed a InstumentalLoadTimeWeaver to do so… and this Weaver needs to run in a special java-agent (spring-agent)… which is really crap on a server… so it really concerned me!

Solution? EclipseLink allows the configuration weaving=false (link)… which just simply disables the dynamic weaving, so no weaver is used and no java-agent is used… hurray…

but… what are the side-effects?

… to weave all applicable class files at build time so that you can deliver pre-woven class files. Consider this option to weave all applicable class files at build time so that you can deliver prewoven class files. By doing so, you can improve application performance by eliminating the runtime weaving step required by dynamic weaving… (http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#Using_EclipseLink_JPA_Weaving)

so its this a solution? i think so 🙂

genericDAO

in my jpa project i needed DAOs… Data Access Objects… and the concept to implement those should be generic… initially this concept is confusing as hell… but after that its kinda cool 🙂

Each Entity needs an DAO and for every entity there are 6 object involved:

  • interfcae GenericDao<T, K>: the main Interface with the basic DAO functions (CRUD(create, read, update, delete))
  • class GenericDaoImpl<T, K>: implements the GenericDao interface.
  • interface <entity>Dao: interface of the entity DAO, implements the GenericDao<<entityType>, <entityPrimaryKeyType>>
  • class <entity>DaoImpl: implementation of the entity Dao. it is extended by the GenericDaoImpl
  • class <entity>: the entity class
  • class <entity>DaoTest: testing rocks 🙂

confused? ok heres the example: partly in pseudo code…

Basic things:
public interface GenericDao<T, K extends Serializable>{
T findById(K id, boolean lock);
List<T> findAll();
T save(T entity);
void delete(T entity);
}

public abstract class GenericDaoImpl<T, K extends Serializable> implements GenericDao<T, K>

public Person{
  int id;
  string name
}

Person Dao:
public interface PersionDao extends GenericDao<Persion, Integer>

public class PersonDaoImpl extends GenericDaoImpl<Person, Integer> implements PersionDao

And thats it… in the GenericDaoImpl are all the methods for all entites and in the PersonDaoImpl the persion stuff…

eclipselink with spring

we decided to use jpa with eclipselink… i actually think this was a good decition, but there are a few problems, when using it with spring… eclipselink needs a LoadTimeWeaver… which can only be loaded by spring, when run with an spring agent… add following argumentline to the VM arguments when run…

-javaagent:${where.ever.it.is}/spring-agent-2.5.6.jar

so unit test need this command… the question, how it will work with maven is completely different… and with mule its an other story…

jpa cache

ok the entityManager in jpa caches… which is normally a good thing… but with OneToMany / ManyToOne mapping its kinda wired… my problem is, that i have an object A and an object B… A has one B… B has a List<A>…

  1. so created a B and persisted it…
  2. created a A with the B object and persited it
  3. checked A and has B 🙂
  4. checked B and has an empty list 🙁

and everything is in one transaction… unit test… if i persist it B with A in the list.. it works… but DB looks exactly the same… so there is a cache…

how can i kill it? or is it really a problem?

see: http://en.wikibooks.org/wiki/Java_Persistence/Caching

jpa mapping

java <-> oracle… with jpa sounds really easy, but was not… ok not really, because i just didnt get the whole thing… a problem was the naming… java class naming is different the database entities… so i needed to add mapping keywords…

@Entity
@Table (name=”<tablename>”, schema=”<schemaname>”)
public class <classname>{

@Id
@Column(name=”<colname>”)
private int id;

ok that was the simple part 🙂 the really hard part was the autoincrement… jpa allows different types of generatedValues and mainly it needs a specified sequence or trigger… the trigger is an absolute no go… and mapping sequence is wired… ok not soooo wired, but…

@Id
GeneratedValue(strategy = GenerationType.SEQUENCE, generator = “<sequenceName>”)
@SequenceGenerator(name = “<sequenceName>”, initialValue = 1, allocationSize = 1)
@Column(name=”<colname>”)
private int id;

the strategy needs an generator, which know the sequence and its behavior… and allocationSize is the increment value… which is 50 as default…