- Storing di un oggetto
private void saveButtonActionPerformed(ActionEvent evt) {
Address address = new Address();
address.setCustomerNo( customerNoText.getText() );
address.setLastname( lastnameText.getText() );
address.setFirstname( firstnameText.getText() );
address.setStreet( streetText.getText() );
address.setPostcode( postcodeText.getText() );
address.setCity( cityText.getText() );
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"JPATutorialPU" );
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist( address );
em.getTransaction().commit();
} catch (Exception e) {
System.out.println( e.getMessage() );
em.getTransaction().rollback();
} finally {
em.close();
}
}
- Lettura di un oggetto
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"JPATutorialPU" );
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
String customerNo = JOptionPane.showInputDialog(
null,
"Enter customer number",
"Input",
JOptionPane.QUESTION_MESSAGE);
try {
Query query = em.createQuery(
"SELECT a FROM Address a WHERE a.customerNo = :customerNo");
query.setParameter(
"customerNo",
customerNo);
Address address = (Address) query.getSingleResult();
customerNoText.setText( address.getCustomerNo() );
lastnameText.setText( address.getLastname() );
firstnameText.setText( address.getFirstname() );
streetText.setText( address.getStreet() );
postcodeText.setText( address.getPostcode() );
cityText.setText( address.getCity() );
} catch (Exception e) {
System.out.println( e.getMessage() );
em.getTransaction().rollback();
} finally {
em.close();
}
}
Nessun commento:
Posta un commento