Wednesday, December 4, 2013

Why is Fetch(join) is not working with HQL?

@Fetch(JOIN) will be ignored if you use the Query interface (e.g.: session.createQuery()) but it will be properly used if you use the Criteria interface.

This is practically a bug in Hibernate which was never resolved. It is unfortunate because a lot of applications use the Query interface and cannot be migrated easily to the Criteria interface.

If you use the Query interface you always have to add JOIN FETCH statements into the HQL manually.

Hibernate Fetch plan and Fetch Strategies

The Hibernate Relations Works with different Fetch Strategies..!!

Hibernate provides 4 strategies for retrieving data:

SELECT

  @OneToMany(mappedBy="tableName", cascade=CascadeType.ALL)  @Column(name="id")   @Fetch(FetchMode.SELECT)

In this Method there are Multiple SQLs fired. This first one is fired for retrieving all the records in the Parent table. The remaining are fired for retrieving records for each Parent Record. This is basically the N+1 problem. The first query retrieves N records from database, in this case N Parent records. For each Parent a new query retrieves Child. Therefore for N Parent, N queries retrieve information from Child table.

JOIN

  @OneToMany(mappedBy="tableName", cascade=CascadeType.ALL)  @Column(name="id")  @Fetch(FetchMode.JOIN) 

This is similar to the SELECT fetch strategy except that fact that all database retrieval take place upfront in JOIN fetch unlike in SELECT where it happens on a need basis. This can become an important performance consideration.

SUBSELECT

   @OneToMany(mappedBy="tableName", cascade=CascadeType.ALL)   @Column(name="id")   @Fetch(FetchMode.SUBSELECT)

Two SQLs are fired. One to retrieve all Parent and the second uses a SUBSELECT query in the WHERE clause to retrieve all child that has matching parent ids.

BATCH

  @OneToMany(mappedBy="tableName", cascade=CascadeType.ALL)  @Column(name="id")  @@BatchSize(size=2)

The batch size maps to the number of Parent whose child are retrieved. So we can specify the number of records to be fetched at a time.But Multiple queries will be executed.!!

one-to-many & many-to-many allows - join, Select and SubSelect

many-to-one & one-to-one allows - Join and Select


Hibernate also distinguishes between (when is the associations are fetched)

1.Immediate fetching -

an association, collection or attribute is fetched immediately, when the Parent is loaded. (lazy="false")

2.Lazy collection fetching -

a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.(lazy="true")

3."Extra-lazy" collection fetching -

individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections) (lazy="extra")

4.Proxy fetching -

a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object. (lazy="proxy")

5."No-proxy" fetching -

a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy.(lazy="no-proxy")

6.Lazy attribute fetching -

an attribute or single valued association is fetched when the instance variable is accessed. (lazy="true")

one-to-many & many-to-many allows Immediate, Layzy, Extra Lazy

many-to-one & one-to-one allows Immediate Proxy, No Proxy

Friday, May 17, 2013

Make log4j display which file it used to configure itself?

Notes to myself:

simply add log4j.debug to the JVM system variables. For example:
java -Dlog4j.debug -cp ... some.class.name

Log4j FAQ

Tuesday, April 30, 2013

Could not create plugin of type 'MatrixTestingPlugin'

After forked and cloned Hibernate-orm project from Github, I tried to compile the project using

./gradlew clean build


But I'm kept getting error:

Could not create plugin of type 'MatrixTestingPlugin'


I checked my environment, I have "JAVA_HOME" configured. I even have had previously installed gradle removed.

Eventually, I figured the problem is that the path of "JAVA_HOME" has the empty space, and gradle 1.5 failed to recognize that. So after moved Java into a location with no space in the path, the problem solved.

Wednesday, April 24, 2013

Very quick takeout of Gradle


  • Gradle is a DSL created with Groovy.
  • Gradle build script is simply Groovy code that drives the Gradle API.
  • As a Java developer, to think of build.gradle script is writing main() method in a class that implemented  Project  interface.
  • Gradle scripts are made of "task"s, an equivalent of "target" in Ant, or "goal" in Maven.
  • There are Plugins available for different languages which includes the "task"s based on languages convention. Such as Java, after added plugin, try gradle tasks to verify what tasks are available.
    apply plugin: 'java'
  • To understand the basic of Gradle, read User Guide chapter 6 Build Script Basics.
  • The ultimate reference for Gradle DSL, all the elements of scripts.
  • To start write build script for Java project. Read User Guide chapter 23. The Java Plugin.





Tuesday, April 23, 2013

Understand most basic concepts of Encryption

When I'm orgnizing my notes, I found this artical. I lost track of origin, but thanks to the author.

1. Traditional encryption(Symmetric): Use the same key to encrypt and decrypt messages.
Problem 0: How to deliver key to the recipients safely?

2. Solution: Asymmetric encryption - A pair of keys, one for encryption(public key), one for decryption(private key). Anybody can have the public key, only the one who has the private key can decrypt the information. The message transformation process becomes the recipient generates a key pair and keeps private key safely, then deliver the public key to the sender(the safety of delivering is not so much concern).
Is it a perfect solution? no.
Problem 1: How could message sender knows the public key is from the recipient wanna be. For example, a spy can capture the carrier and forge a pair of key, and send his or her public key to the sender, then after the encrypted message comes back, decrypt it, do some damages then use the original public key to encrypt it, then send to real recipient.

3. Solution: Need a way to identify the public key is from the real recipient wanna be. Think of money, it is actually just a piece of paper, but why everyone accepts the value that money represents, because it is issued by government. Government has the ultimate power(it supports by police and army), with his authorization, everyone accepts it, otherwise will be punished. The same concept, if a party has this kind of ultimate power can put a signature to prove the owner of the public key. Then message sender can trust the public key is from right person who claims to be. Fortunately, there's this kind of parties, but they are not supported by any kind of police or army, it is supported by conceptually unbreakable security and well respected reputation. This kind of party called CA(Certification Authority). Sound like not that reliable like government.

Then the public key is not the only thing to be delivered to message sender, you deliver a bundle with: Public key to be used to encrypt message, the public key issuer's personal information, issuer's signature, and CA's signature of course. This bundle called Digital Certificate.

Is it perfect now? no.
Problem 2: Asymmetric encryption and decryption is 1000 times slower then symmetric algorithm. Looks how impatient today's people are.

4. Solution: Combination of symmetric and asymmetric to speed up. You can do like, encrypt the original message with traditional way(symmetric) with a random generated key, but encrypt this one time random key with public key, then send encrypted message together with asymmetric encrypted key. Because for asymmetric algorithm, the smaller message, the faster encryption. The symmetric key is most time much smaller than the original message.

Digital digest (Hash functions) - A very short message(digital digest) can be generated from no matter how big the original message is. For example, 160-bits. The magic is that this short message is reproducible with the same algorithm, and even a tiny little bit change in the original message, the digital digest will be completely different.

How to query on key of map collection in Hibernate?


Until Hibernate implements JPA's key() function (see HHH-5396), you can use the index() function:
Query q = session.createQuery("select a from TestA a join a.testBMap m where index(m) = :key");
q.setParameter("key", "test1");
q.list();

Matrix Parameters and Query Parameters

Just to remind myself the concepts of:
Query parameters: http://example.com/apples?order=random&color=blue
Matrix parameters: http://example.com/apples;order=random;color=blue


- Maxtrix parameters is not commonly used.

- Matrix parameters can make RESTful URL more expressive.

- JAX-RS supports matrix parameters. Spring MVC supports it since 3.2.

- Servlet container uses ;jsessionid=xxx in the URI when client cookies is disabled, this is called URL-Rewriting.
Google+