Hi -- I've got what I think is a simple question. I've seen examples both ways. The question is - "why can't I place my annotations on the field?". Let me give you an example....
@Entity
@Table(name="widget")
public class Widget {
private Integer id;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Integer getId() { return this.id; }
public Integer setId(Integer Id) { this.id = id;}
}
The above code works fine (assuming there's not a typo in there). When the annotation is placed on the getter of the property everything is perfect.
However, that seems awkward to me. In my mind it's cleaner to place the annotation on the field, like so --
@Entity
@Table(name="widget")
public class Widget {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
public Integer getId() { return this.id; }
public Integer setId(Integer Id) { this.id = id;}
}
I've seen examples of both ways. However, when I run this second example I get the following...
java.lang.NullPointerException at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:25) at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:1) at java.lang.ThreadLocal$ThreadLocalMap.getAfterMiss(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.get(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.access$000(Unknown Source) at java.lang.ThreadLocal.get(Unknown Source) at com.widget.util.hibernate.HibernateSessionFactory.get(HibernateSessionFactory.java:33) at com.widget.db.dao.AbstractDao.(AbstractDao.java:12) at com.widget.db.dao.WidgetDao.(WidgetDao.java:9) at com.widget.db.dao.test.WidgetDaoTest.findById(WidgetDaoTest.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) ...
Here's the skeleton of HibernateSessionFactory
(line 25 is marked) ....
protected Session initialValue() {
SessionFactory sessionFactory = null;
try {
Configuration cfg = new AnnotationConfiguration().configure();
String url = System.getProperty("jdbc.url");
if (url != null) {
cfg.setProperty("hibernate.connection.url", url);
}
sessionFactory = cfg.buildSessionFactory();
}
catch (Exception e) {
}
Session session = sessionFactory.openSession(); // LINE 25
return session;
}
Anyone have an idea what's going on here?