我创建了一个简单的程序,该程序将询问用户其用户名,并且一切正常,直到进行身份验证为止。我已经将数据手动插入数据库中以进行测试,现在我想通过检查用户是否输入了与数据库中相同的用户名来验证用户的登录名。但是,当我询问管理员对象的吸气剂时,将返回空值。
有人可以帮我解释为什么数据在数据库中时会返回null吗?谢谢。
供参考:
public void actionPerformed(ActionEvent e) {
//objects for connection
//Testing
Administrator cevo = new Administrator();
//==========================================//
Session session = HibernateUtility.getSessionFactory().openSession();
session.beginTransaction();
if (username.getText().equals(cevo.getGivenName())) { //Returned Value is Null, but data is present in DB.
System.out.println("MATCH");
}
else{
System.out.println(cevo.getGivenName());
System.out.println(username.getText());
System.out.println("NO MATCH");
}
session.clear();
session.close();
}
});
}
这是我的管理员类,仅供参考:
@Entity()
@Table(name = "ADMINISTRATOR", schema = "registrationsystem")
public class Administrator implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@JoinColumn(name ="ID", nullable = false)
protected int ID;
@Column(name = "NAME")
protected String name;
@JoinColumn(name = "FAMILYNAME")
//@OneToOne(mappedBy = "familyname", fetch = FetchType.LAZY)
protected String familyName;
@JoinColumn(name = "AGE")
//@OneToOne(mappedBy = "age", fetch = FetchType.LAZY)
protected int age;
@JoinColumn(name = "OCCUPATION")
// @OneToOne(mappedBy = "occupation", fetch = FetchType.LAZY)
protected Occupation occupation;
public Administrator() {
}
public String getGivenName() {
return name;
}
public void setGivenName(String givenName) {
this.name = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Occupation getOccupation() {
return occupation;
}
public void setOccupation(Occupation occupation) {
this.occupation = occupation;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
答案 0 :(得分:1)
您的代码似乎有点混乱,因为您实际上没有查询数据库中的任何内容。
Administrator cevo = new Administrator();
if (username.getText().equals(cevo.getGivenName())) {
System.out.println("MATCH");
}
很明显cevo.getGivenName()
返回null,因为它尚未初始化。仅仅因为您从事务内部的任意对象中调用方法并不意味着它会自动获取相应的数据库对象。 Hibernate功能丰富,但最终并不是魔术。
您应尝试查询管理员。这里有一些提示:
Query query = session.createQuery("select Administrator where id = :admin_id");
query.setParameter("admin_id", 1);
Administrator result = (Administrator) query.getSingleResult();