zwwcn

Just another WordPress.com site

Monthly Archives: October 2016

hibernate criteria on composite id

@Embeddable
public class TeacherStudentPK  implements java.io.Serializable{
    @ManyToOne
    @JoinColumn(name = "STUDENT_ID")
	private Student student;
    @ManyToOne
    @JoinColumn(name = "TEACHER_ID")
public class TeacherStudent implements java.io.Serializable {

	/* primay key*/
	@EmbeddedId 
	private TeacherStudentPK teacherStudentPK;
      public class Student{
	@OneToMany(mappedBy="teacherStudentPK.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))
									
Advertisements

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:

     ......
     saveNote(note);
     em.flush();
     AddNoteToJMSQueue(note);
    public void createThumbnail(Note note){
        Note note = em.merge(note);
        createThumbnailMethod(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){
           ctx.setrollbackOnly();
        }
        createThumbnailMethod(note);
    }