访问存储在persistence.xml中的数据库

时间:2014-01-16 13:29:52

标签: java java-ee servlets netbeans

我想访问我在Netbeans中的persistence.xml中设置的数据库。

我有一些示例代码似乎使用EntityManager和UserTransaction将人员对象存储在数据库中,但我想知道是否需要对简单的SELECT查询使用相同的东西?

@WebServlet(name="CreatePersonServlet", urlPatterns={"/CreatePerson"})
public class CreatePersonServlet extends HttpServlet {

@PersistenceUnit
//The emf corresponding to 
private EntityManagerFactory emf;  

@Resource
private UserTransaction utx;


/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
    assert emf != null;  //Make sure injection went through correctly.
    EntityManager em = null;
    try {

        //Get the data from user's form            
        String firstName  = (String) request.getParameter("firstName");
        String lastName   = (String) request.getParameter("surname");
        String address   = (String) request.getParameter("address");
        String dobString   = (String) request.getParameter("dob");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dob = formatter.parse(dobString);
        String email      = (String) request.getParameter("email");
        String phone      = (String) request.getParameter("phone");
        String password   = (String) request.getParameter("password");
        boolean isAdmin = false;


        //Create a person instance out of it
        Customer person = new Customer(firstName, lastName, dob, email, phone, password, isAdmin);

        //begin a transaction
        utx.begin();
        //create an em. 
        //Since the em is created inside a transaction, it is associsated with 
        //the transaction
        em = emf.createEntityManager();
        //persist the person entity
        em.persist(person);
        //commit transaction which will trigger the em to 
        //commit newly created entity into database
        utx.commit();

        //Forward to ListPerson servlet to list persons along with the newly
        //created person above
        request.getRequestDispatcher("ListPerson").forward(request, response);
    } catch (Exception ex) {
        throw new ServletException(ex);
    } finally {
        //close the em to release any resources held up by the persistence provider
        if(em != null) {
            em.close();
        }
    }
}

我设法使用手动连接字符串来做我想要的事情:

Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mydb","mydb", "mypassword");

PreparedStatement ps = conn.prepareStatement("select * from Customer where Email=? and Password=?"); 

是否有更简单的方法来访问数据库,因为它已经设置为持久性?

2 个答案:

答案 0 :(得分:0)

我认为这取决于你想做什么。如果需要Customer对象列表,请使用createQuery()创建一个返回Customer列表的查询。

如果您真的想要任意SQL,请让您的实体经理执行本机查询。

entityManager.createNativeQuery('select foo from bar');

您可能希望阅读所有http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html以查看它可以执行的操作。

答案 1 :(得分:0)

通常的方法是在您的实体类中定义NamedQuery,因为它变得比数据库不可知,您可以从缓存中受益。所以尝试像

这样的东西
@NamedQueries({
    @NamedQery(name = "customerByMailAndPassword"
               query = "select * from Customer where Email=? and Password=?")
})
@Entity
public class Customer {}

然后像这样使用它

Customer c = em.createNamedQuery("customerByMailAndPassword")
    .setParameter(1, "mail@mail.com")
    .setParameter(2, "psswd")
    .getSingleResult();