Java 访问persistence.xml中存储的数据库
我想访问我在Netbeans的persistence.xml中设置的数据库 我有一些示例代码似乎使用EntityManager和UserTransaction在数据库中存储person对象,但我想知道是否需要在简单的SELECT查询中使用相同的东西Java 访问persistence.xml中存储的数据库,java,jakarta-ee,servlets,netbeans,Java,Jakarta Ee,Servlets,Netbeans,我想访问我在Netbeans的persistence.xml中设置的数据库 我有一些示例代码似乎使用EntityManager和UserTransaction在数据库中存储person对象,但我想知道是否需要在简单的SELECT查询中使用相同的东西 @WebServlet(name="CreatePersonServlet", urlPatterns={"/CreatePerson"}) public class CreatePersonServlet extends HttpServlet {
@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=?");
有没有更简单的方法来访问数据库,因为它已经在持久性中设置好了?我认为这取决于您想做什么。如果需要客户对象列表,请使用createQuery()创建一个查询,该查询将返回客户对象列表 如果您真的想使用任意SQL,请让您的实体管理器执行本机查询
entityManager.createNativeQuery('select foo from bar');
您可能想阅读所有这些内容,看看它能做些什么。通常的方法是在实体类中定义,因为它变得与数据库无关,并且您可以从缓存中获益。所以试试类似的方法
@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();
使用JPA从数据库中获取对象比使用普通JDBC要简单得多,特别是如果您已经拥有实体的话。它可以像em.find(Customer.class,idOfCustomer)一样简单。