通过hibernate从数据库中检索对象

时间:2013-05-04 14:44:45

标签: java hibernate persistence

我正在创建一个hibernate应用程序,我可以通过hibernate将数据保存到dtb。然而,我无法弄清楚,如何从数据库中检索数据。任何人都可以告诉我,如何以某种方式做到这一点,这将类似于我保存数据的方式?我一直在谷歌搜索,但一切,我没有找到任何东西,这看起来像我的方式...例如。他们使用了大量的注释等。我对hibernate很新,所以有可能,这不是一个好方法,如何创建hibernate应用程序。如果是这样,请将其写在评论中。

UserDAOImpl的一部分:

UserDAO user;

public UserDAOImpl() {
    user = new UserDAO();
}

public void createUser(int id, String Username, String CreatedBy) {
    user.setUserId(id);
    user.setUsername(Username);
    user.setCreatedBy(CreatedBy);
    user.setCreatedDate(new Date());
}

public void saveUser() {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();      
   session.save(user);
   // save the data to the database
   session.getTransaction().commit();
   // close the connection
   session.disconnect();
}


public void findUser() {
     // ????????????
}

UserDAO的:

public class UserDAO implements java.io.Serializable {

    /**
     * generated serialVersionUID
     */
    private static final long serialVersionUID = -6440259681541809279L;

    private int userId;
    private String username;
    private String createdBy;
    private Date createdDate;

    public UserDAO() {
    }

    public UserDAO(int userId, String username, String createdBy,
            Date createdDate) {
        this.userId = userId;
        this.username = username;
        this.createdBy = createdBy;
        this.createdDate = createdDate;
    }

    public int getUserId() {
        return this.userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getCreatedBy() {
        return this.createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedDate() {
        return this.createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    } 
}

2 个答案:

答案 0 :(得分:1)

假设表名是User,下面是获取输入userId的用户数据的示例代码:

public User findUserById(int userId) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   String queryString = "from User where userId = :userId";  
   Query query = session.createQuery(queryString);  
   query.setInteger("userId", userId);  
   Object queryResult = query.uniqueResult();  
   UserDAO user = (UserDAO)queryResult;
}

答案 1 :(得分:0)

最后,我在SO的另一个帖子中找到了答案。

// finds user by ID
public UserDAO findUserById(int userId) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session = HibernateUtil.getSessionFactory().openSession();
    UserDAO userDAO = (UserDAO) session.get(UserDAO.class, userId);
    session.disconnect();
    return userDAO;
}