I am using struts2-fullhibernatecore-plugin-2.2.2-GA.jar
to inject a session
in my DAO class like below:
public class UserDAO {
@SessionTarget
Session session;
@TransactionTarget
Transaction transaction;
public List<User> getUsers() {
return session.createQuery("from user").list();
}
}
But I got
java.lang.NullPointerException
com.wudi.DAO.UserDAO.getUsers(UserDAO.java:28)
com.wudi.action.UserListAction.execute(UserListAction.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
...
According to debugging output, session
and transaction
in the UserDAO
are null
.
Some files for reference:
User.java
:
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue
private int id;
@Column
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserListAction.java
:
public class UserListAction extends ActionSupport {
private List<User> users;
private UserDAO userDAO = new UserDAO();
@Override
public String execute() throws Exception {
users = userDAO.getUsers();
return SUCCESS;
}
}
hibernate.cfg.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.pool_size">10</property>
<mapping class="com.wudi.model.User" />
</session-factory>
</hibernate-configuration>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…