我是 hibernate 的新手。现在尝试使用 hibernate 将用户详细信息保存到我的数据库中。为此,我创建了 3 个 .java 文件。
1.首先是HiberUtil.java。代码如下包hiberpack;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HiberUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
2.next是DbMap.java
package hiberpack;
import javax.persistence.Column;
import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_details")
public class DbMap {
@Id
//@GeneratedValue
@Column(name = "id")
private long id_auto;
@Column(name = "name", nullable = false)
private String username;
@Column(name = "Smobile", nullable=false)
private String mobnum;
public long getId_auto() {
return id_auto;
}
public void setId_auto(long id_auto) {
this.id_auto = id_auto;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMobnum() {
return mobnum;
}
public void setMobnum(String mobnum) {
this.mobnum = mobnum;
}
}
3.下面是UserSave servlet
package servlets;
import hiberpack.DbMap;
import hiberrepo.Repository;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserSave extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Repository rep = new Repository();
String name = request.getParameter("uname");
String mp = request.getParameter("mob");
DbMap st = new hiberpack.DbMap();
st.setUsername(name);
st.setMobnum(mp);
rep.insertStock(st);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
4.下面是Repository.java
package hiberrepo;
import hiberpack.HiberUtil;
import hiberpack.DbMap;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class Repository {
SessionFactory sf = HiberUtil.getSessionFactory();
Session sfSession = null;
public void insertStock(DbMap storeObj)
{
sfSession.save(storeObj);
}
}
它显示空指针异常,当我尝试使用休眠将数据输入数据库时。错误消息如下
java.lang.NullPointerException
hiberrepo.Repository.insertStock(Repository.java:15)
servlets.UserSave.doPost(UserSave.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)