我开始使用Hibernate并遵循javabrains的教程。但buildsessionfactory
似乎已被弃用。我搜索并找到了solution。
但是,当我尝试从数据库中获取对象时,我在最后一行的sysout处得到NullPointerException
,并且甚至没有条目保存到数据库中。但是,如果我注释掉对象检索部分,它可以正常工作并保存到数据库中。
我做错了什么?
public class HibernateTest {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("User's name");
user.setAddress("Chingeltei");
user.setJoinedDate(new Date());
user.setDescription("Description of the user");
Session session = configureSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
// user = null;
// session = configureSessionFactory().openSession();
// session.beginTransaction();
// user = (UserDetails) session.get(UserDetails.class, 1);
// System.out.println("User name retreived is: "+user.getUserName());
}
}
UserDetails.java
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
@Entity
@Table (name="user_details")
public class UserDetails {
@Id
@Column (name="userid")
private int userId;
@Column (name="username")
private String userName;
@Temporal (TemporalType.DATE)
private Date joinedDate;
private String address;
@Transient
private String description;
public int getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public Date getJoinedDate() {
return joinedDate;
}
public String getAddress() {
return address;
}
public String getDescription() {
return description;
}
public void setUserId(int aUserId) {
userId = aUserId;
}
public void setUserName(String aUserName) {
userName = aUserName;
}
public void setJoinedDate(Date aJoinedDate) {
joinedDate = aJoinedDate;
}
public void setAddress(String aAddress) {
address = aAddress;
}
public void setDescription(String aDescription) {
description = aDescription;
}
}
答案 0 :(得分:1)
正如教程所述,您应该为每个应用程序创建一次sessionFactory
。因此,您应该使用已存在的configureSessionFactory()
引用,而不是第二次调用sessionFactory
。