Just another site

Hibernate exception: duplicate association path

Hibernate doesn’t provide function to check existing alias. If you try to add the same alias to the criteria, you will get exception: duplicate association path.

The solution is to create a set and record all exisitng alias. We only add new alias if it’s not in the set.

private List<String> aliasValues = new ArrayList<>();

Javascript drawing on an image inside a canvas

I just finished a task: load an image inside a popup canvas then draw lines on the canvas and save the image data. I had a couple issues during the development, but luckily I managed to find answers on google.

  1. How to draw on canvas on mobile devices.
    I found a good article which give all the details Using Touch Events with the HTML5 Canvas.  You should be aware of the difference code for IOS,Android and canvas in browser. The touch devices use “touchmove”,”touchstart” while the browswer uses “mousemove”,”mousedown”..etc
  2. We need to stop page scrolling when user are ready for drawing.
    stopScroll = (ev) ->
    $page.on("popupbeforeposition","#popupPanel", (event,ui) ->
    $page.on("popupafterclose","#popupPanel",(event,ui) ->
  3. How to improve image quality.
    When loading the photo to canvas, you may get a blurry image. The following code improve the quality of image

    canvastx = popupCanvas.getContext("2d");
    canvastx.webkitImageSmoothingEnabled = false;
    canvastx.mozImageSmoothingEnabled = false;
    canvastx.imageSmoothingEnabled = false;
  4. Don’t resize canvas, you should always create new one.
    Make sure you create new canvas after reading the image info. This way you know the image demision, then you could create new canvas with the same width/height ratio.  If you draw on a resized canvas,  everything(x,y point) on that canvas will be scaled.  You will have to do some calculation to get the orginal point. That’s why I prefer creating a new canvas with the right size.

Endless loop with ListIterator .hasNext()

The following code will create an endless loop because java creates new iterator everytime you call list.iterator():


We should do it this way:

Iterator iterator = someList.iterator();

POI read cell value as string

When you get error for reading cell value as string:

Cannot get a numeric value from a text cell
or Cannot get a boolean value from a text cell

The code below will format the cell properly and return string value:

final DataFormatter df = new DataFormatter();
final XSSFCell cell = row.getCell(cellIndex);
String valueAsString = df.formatCellValue(cell);

Request URI too long

I had a task to add a link in a chart. Depends on the area user clicks,  the system will create a get request, forward the user to next page.  The URL looks like “http://localhost:8080/nextpage?q=para1:1,2,3,4;para2:3,2,2,3;para3:test1,test2,test..”. The URL becomes too long and gives an error in the browser: request URI too long.

All we need to do is to change the request to post request. We create a hidden form on the page, which contains one input field and one button. the input field is used to save the parameters value (q in the example), and when user click the chart. I set the parameters value to the input field, then trigger a click on the button to submit the form.

And the code in javascript listener:


Jquery mobile multiple select with many options

When multiple select has too many options, jquery mobile will open a dialog rather than popup, which is a new page. Every time the popup is closed the pagecontainerbeforeload and pagecontainershow events are triggered again and thereby the initialisation code. We could add a check on the prevPage to avoid unwanted initialisation.

    $(document).on( "pagecontainerbeforeload", function( event, data ) {
         ......initialisation code....

Create copy of a list

Sometimes we want to pass a list as parameter to a method, we will do some work on the list but don’t want to affect the origin list.

The code below is not good, as we are passing the orginal reference to the method, all changes will affect the orginal list


Instead, we should do something like:

     DoSomeWork(new ArrayList(SelectedPerson.getAllAddresses()));

Pleaes be awared that the second example passed a copy of the list to DoSomeWork, but the elements in the copy still hold reference to the orginal elements. Modifying any object element in the copy list will also change the element in the original.

hibernate criteria on composite id

public class TeacherStudentPK  implements{
    @JoinColumn(name = "STUDENT_ID")
	private Student student;
    @JoinColumn(name = "TEACHER_ID")
public class TeacherStudent implements {

	/* primay key*/
	private TeacherStudentPK teacherStudentPK;
      public class Student{
	private Collection teachers = new ArrayList();

The crieteria is shown below:

criteria = em.createCriteria(Student.class, "student")
		   .createAlias("student.teachers", "teacherStudent")
.add(Restrictions.eq("teacherStudent.teacherStudentPK.teacher", selectedTeacher))

JMS queue listener

Let’s say we are saving a note along some pics into the database. We will need to resize the pics and only save thumbnails. The resizing images part could take a couple seconds and we don’t want user to wait on the page, so we do it asynchronously.

The workflow would be: 1 save note;  2 flush session; 3 send resizing images request to jms ; 4 JMS queue listener receive the msg and find service action to create thumbnail.

During the resizing image process, I need to link the resized images to the note and then save the thumbnail. I had some code like below:

    public void createThumbnail(Note note){
        Note note = em.merge(note);

This doesn’t work because the process is asynchronous, when the resizing starts in JMS the note may not be in the database yet. What I had in my case the createThumbnail method then create another record for note, so I have duplicate record in the database.

To solve this problem, we should use find to look up the record in database before perform any action. If we can’t find the record in database then we should rollback and retry in JMS.

so the code goes:

    public void createThumbnail(Note note){
        Note newNote = em.find(note);
        if(newNote == null){


singtonMap and singletonList allow you quickly create an unmodifiable collection:

methodTakesAMap(Collections.singletonMap(key, value));

rather than this:

Map<KeyType, ValueType> m = new HashMap<KeyType, ValueType>();
m.put(key, value);

singletonList example:

List sampleList = collections.singletonList("theOnlyOption");