by
1
6
2,250
0
Top 1% !
Popular
Famous
Tagged
Specified
OpenSource
Popularity: 8622nd place

Published on:

Languagejava
LicenseMIT_X11

How to integrate JAXB and JPA annotations in java

This example shows how to integrate JAX-B and JPA annotations and methods to marshal/unmarshal java objects from xml and persist and access data on database.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/43629/How-to-integrate-JAXB-and-JPA-annotation?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
package com.examples.jpa.tests; import com.examples.jpa.*; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.LockModeType; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.Selection; import javax.xml.bind.JAXB; public class EntityTests { private final static EntityManagerFactory entityManagerFactory; static { entityManagerFactory = Persistence.createEntityManagerFactory("MyNativeJPAProject"); } public EntityTests() { // createNetwork(); // testOptimisticLock(); // printEquipment(); // testDeleteOrphan(); // printEquipment(); // testCriteria(); Network network = createNetwork(); JAXB.marshal(network, new File("out.xml")); network = null; network = JAXB.unmarshal(new File("out.xml"), Network.class); if (network != null) { System.out.println(network); String id = network.getId(); network = null; network = selectNetwork(id); if (network != null) { System.out.println(network); } else { System.out.println("Select Null!"); } } else { System.out.println("Unmarshal Null!"); } } public static void main(String[] args) { new EntityTests(); } private Network selectNetwork(String networkId) { Network network = null; network = findNetwork(networkId); return network; } public Network findNetwork(String id) { Network network = null; EntityManager entityManager = entityManagerFactory.createEntityManager(); try { String jpql = "SELECT n FROM Network n WHERE n.id = :id"; TypedQuery<Network> query = entityManager.createQuery(jpql, Network.class); query.setParameter("id", id); network = query.getSingleResult(); } catch (Exception e) { e.printStackTrace(); } finally { entityManager.close(); } return network; } private Network createNetwork() { Network network = new Network(); Equipment e1 = new Equipment("Eqt 1"); EquipmentController ctrl1 = new EquipmentController("Ctrl 1"); ctrl1.setControllerAddress(new ControllerAddress("194.23.4.1", 4447)); e1.setEquipmentController(ctrl1); Card c1 = new Card("Crd:1.1"); Port p11 = new EthernetPort("Prt:1.1.1", 1526, 1000, true); c1.addPort(p11); Port p12 = new EthernetPort("Prt:1.1.2", 1024, 100, true);; c1.addPort(p12); e1.addCard(c1); Card c2 = new Card("Crd:1.2"); Port p21 = new SdhPort("Prt:1.2.1", true, 2488, VirtualContainer.VC12); p21.setCard(c2); c2.addPort(p21); Port p22 = new EthernetPort("Prt:1.2.2", 1526, 1000, true); c2.addPort(p22); Port p32 = new EthernetPort("Prt:1.2.3", 1024, 2048, true); c2.addPort(p32); e1.addCard(c2); Equipment e2 = new Equipment("Eqt 2"); EquipmentController ctrl2 = new EquipmentController("Ctrl 2"); ctrl2.setControllerAddress(new ControllerAddress("194.23.4.222", 1122)); e2.setEquipmentController(ctrl2); Card c22 = new Card("Crd:1.2"); Port p212 = new EthernetPort("Prt:1.1.2", 1526, 1000, true); c22.addPort(p212); Port p2123 = new EthernetPort("Prt:1.1.3", 1024, 100, true);; c22.addPort(p2123); e2.addCard(c22); network.addEquipments(e1); network.addEquipments(e2); save(network); return network; } private void printEquipment() { EntityManager entityManager = entityManagerFactory.createEntityManager(); try { TypedQuery<Equipment> query = entityManager.createQuery("SELECT e FROM Equipment e", Equipment.class); List<Equipment> equipments = query.getResultList(); for (Equipment equipment : equipments) { NetworkUtils.print(equipment, System.out); } } catch (Exception e) { e.printStackTrace(); } finally { entityManager.close(); } } public void deleteEquipment() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { TypedQuery<Equipment> query = entityManager.createQuery("SELECT e FROM Equipment e", Equipment.class); List<Equipment> equipments = query.getResultList(); for (Equipment equipment : equipments) { transaction.begin(); entityManager.detach(equipment); transaction.commit(); } } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } private void testDeleteOrphan() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { TypedQuery<Equipment> query = entityManager.createQuery("SELECT e FROM Equipment e", Equipment.class); List<Equipment> equipments = query.getResultList(); transaction.begin(); for (Equipment equipment : equipments) { List<Card> cards = equipment.getCards(); for (Iterator<Card> i = cards.iterator(); i.hasNext();) { Card card = i.next(); if ("Crd:1.1".equals(card.getLabel())) { i.remove(); } card.setEquipment(null); } entityManager.merge(equipment); } transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } private void createEquipment() { Equipment e1 = new Equipment("Eqt 1"); EquipmentController ctrl1 = new EquipmentController("Ctrl 1"); ctrl1.setControllerAddress(new ControllerAddress("194.23.4.1", 4447)); e1.setEquipmentController(ctrl1); Card c1 = new Card("Crd:1.1"); Port p11 = new EthernetPort("Prt:1.1.1", 1526, 1000, true); c1.addPort(p11); Port p12 = new EthernetPort("Prt:1.1.2", 1024, 100, true);; c1.addPort(p12); e1.addCard(c1); Card c2 = new Card("Crd:1.2"); Port p21 = new SdhPort("Prt:1.2.1", true, 2488, VirtualContainer.VC12); p21.setCard(c2); c2.addPort(p21); Port p22 = new EthernetPort("Prt:1.2.2", 1526, 1000, true); c2.addPort(p22); Port p32 = new EthernetPort("Prt:1.2.3", 1024, 2048, true); c2.addPort(p32); e1.addCard(c2); save(e1); } private Card findCardByLabel(String label) { EntityManager entityManager = entityManagerFactory.createEntityManager(); try { TypedQuery<Card> query = entityManager.createQuery("SELECT c FROM Card c WHERE c.label = :label", Card.class); query.setParameter("label", label); Card card = query.getSingleResult(); return card; } finally { entityManager.close(); } } private void save(Equipment e1) { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); entityManager.persist(e1); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } private void save(Network n) { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); entityManager.persist(n); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } private void testCriteria() { EntityManager entityManager = entityManagerFactory.createEntityManager(); try { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<String> criteria = builder.createQuery(String.class); Root portRoot = criteria.from(Port.class); criteria.select(portRoot.get("label")); Path<Object> cardLabelPath = portRoot.get("card").get("label"); Predicate whereCondition = builder.equal(cardLabelPath, "Crd:1.1"); criteria.where(whereCondition); List<String> portLabels = entityManager.createQuery(criteria).getResultList(); for (String portLabel : portLabels) { System.out.println("Port label: " + portLabel); } } catch (Exception e) { e.printStackTrace(); } finally { entityManager.close(); } } private void testOptimisticLock() { Thread t1 = new Thread() { @Override public void run() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class); query.setLockMode(LockModeType.OPTIMISTIC); query.setParameter("portLabel", "Prt:1.2.1"); Port port = query.getSingleResult(); System.out.println("Thread 1: Lock obtained"); this.sleep(10000); port.setDescription("Changed"); entityManager.merge(port); transaction.commit(); System.out.println("Thread 1: Transaction commited and lock released"); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } }; t1.start(); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(EntityTests.class.getName()).log(Level.SEVERE, null, ex); } Thread t2 = new Thread() { @Override public void run() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class); query.setLockMode(LockModeType.OPTIMISTIC_FORCE_INCREMENT); query.setParameter("portLabel", "Prt:1.2.1"); System.out.println("Thread 2: Waiting for read Port"); Port port = query.getSingleResult(); System.out.println("Thread 2: Port is: "+port); port.setDescription("SDH port"); entityManager.merge(port); transaction.commit(); System.out.println("Thread 2: Transaction commited"); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } }; t2.start(); } private void testPessimisticLock() { Thread t1 = new Thread() { @Override public void run() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class); query.setLockMode(LockModeType.PESSIMISTIC_WRITE); query.setParameter("portLabel", "Prt:1.2.1"); Port port = query.getSingleResult(); System.out.println("Thread 1: Lock obtained"); this.sleep(10000); transaction.commit(); System.out.println("Thread 1: Transaction commited and lock released"); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } }; t1.start(); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(EntityTests.class.getName()).log(Level.SEVERE, null, ex); } Thread t2 = new Thread() { @Override public void run() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class); query.setLockMode(LockModeType.PESSIMISTIC_READ); query.setParameter("portLabel", "Prt:1.2.1"); System.out.println("Thread 2: Waiting for read Port"); Port port = query.getSingleResult(); System.out.println("Thread 2: Port is: "+port); transaction.commit(); System.out.println("Thread 2: Transaction commited"); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } }; t2.start(); } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus