Java – Unmarshaller using JAXB binding

The generated package has been generated by JAXB and the classes where generated too.

/**
* This method open, read and unmarshall a file
* @param URLFichier url of the file to open
* @return an entity object
*/
public MyEntity readFile (String URLfile){

 try {
   JAXBContext jc = JAXBContext.newInstance("generated"); //this is the name of the generated package
   Unmarshaller unmarshaller = jc.createUnmarshaller();
 
   File fileXML = new File(URLfile);
   JAXBElement parseResult = (JAXBElement) unmarshaller.unmarshal(fileXML);
   MyEntity myEntity = (MyEntity) parseResult.getValue();
 } 
 catch (JAXBException ex) {
   System.out.println("Erreur JAXB : " + ex.getMessage());
 } 
 catch (ClassCastException ex) {
   System.out.println("Erreur lors du cast : " + ex.getMessage());
 }
}

Java – DataBase access – basic class

This is a basic class to access a database using a persistence.xml file. This class has already 3 methods to handle the transactions.

public class DBaccess {

    private final EntityManagerFactory factory;
    private final EntityManager manager;
    private EntityTransaction transaction;

    public DBaccess() {
        factory = Persistence.createEntityManagerFactory("myPersistenceUnit");
        manager = factory.createEntityManager();
    }

    private void startTransaction() {
        transaction = manager.getTransaction();
        transaction.begin();
    }

    private void commit() {
        if (transaction != null) {
            transaction.commit();
        }
        transaction = null;
    }

    private void rollback() {
        if (transaction != null) {
            transaction.rollback();
        }
        transaction = null;
    }
}