I am new to Hibernate. I have found out that we can have event listener in Hibernate which will notify us of changes made on DB. What I am interested in is Will the Java code be called if I am not doing any DB changes through Java application but only through DB. Here is what I have coded::
Hibernate CFG file and Corresponding HBM file
Code:
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url"></property>
<property name="hibernate.connection.username"></property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size"></property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<!-- Mapping files -->
<mapping resource="hbm/ps.hbm.xml"/>
<listener type="post-insert" class="com.Dummy"/>
</session-factory>
</hibernate-configuration>
<hibernate-mapping>
<class name="com.Bean" table="Demo">
<id name="id" type="string" column="ID" />
<property name="name" type="string" column="NAME"></property>
</class>
Listener Class implementing PostInsertListener::
Code:
import org.hibernate.Session;
import org.hibernate.event.PostInsertEvent;
import org.hibernate.event.PostInsertEventListener;
public class Dummy implements PostInsertEventListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void onPostInsert(PostInsertEvent event) {
// TODO Auto-generated method stub
System.out.println(event.getEntity() instanceof Bean);
System.out.println("Inside onPostInsert");
Session session = event.getSession();
System.out.println(session.toString());
}
}
Main Class::
Code:
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
System.out.println("Here");
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Bean bean= new Bean();
bean.setId("4");
bean.setName("Dummy");
System.out.println("Before Insert");
session.save(bean);
System.out.println("After Save");
tx.commit();
System.out.println("After Commit");
session.close();
factory.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
The code works magic when i run the main class Inserts into DB as it should call the onPostInsert method as expected but if i run the application and make changes from DB ie insert a column the Console doesnt print anything. Is there something I am missing?? I am using SQL server...are there any compatibility issue with SQL server?? It is a plain java application nothing much