use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.
the class HelloWorldJPA method storeLoadMessage.
@Test
public void storeLoadMessage() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloWorldPU");
try {
{
/*
Get access to the standard transaction API <code>UserTransaction</code> and
begin a transaction on this thread of execution.
*/
UserTransaction tx = TM.getUserTransaction();
tx.begin();
/*
Begin a new session with the database by creating an <code>EntityManager</code>, this
is your context for all persistence operations.
*/
EntityManager em = emf.createEntityManager();
/*
Create a new instance of the mapped domain model class <code>Message</code> and
set its <code>text</code> property.
*/
Message message = new Message();
message.setText("Hello World!");
/*
Enlist the transient instance with your persistence context, you make it persistent.
Hibernate now knows that you wish to store that data, it doesn't necessarily call the
database immediately, however.
*/
em.persist(message);
/*
Commit the transaction, Hibernate now automatically checks the persistence context and
executes the necessary SQL <code>INSERT</code> statement.
*/
tx.commit();
// INSERT into MESSAGE (ID, TEXT) values (1, 'Hello World!')
/*
If you create an <code>EntityManager</code>, you must close it.
*/
em.close();
}
{
/*
Every interaction with your database should occur within explicit transaction boundaries,
even if you are only reading data.
*/
UserTransaction tx = TM.getUserTransaction();
tx.begin();
EntityManager em = emf.createEntityManager();
/*
Execute a query to retrieve all instances of <code>Message</code> from the database.
*/
List<Message> messages = em.createQuery("select m from Message m").getResultList();
// SELECT * from MESSAGE
assertEquals(messages.size(), 1);
assertEquals(messages.get(0).getText(), "Hello World!");
/*
You can change the value of a property, Hibernate will detect this automatically because
the loaded <code>Message</code> is still attached to the persistence context it was loaded in.
*/
messages.get(0).setText("Take me to your leader!");
/*
On commit, Hibernate checks the persistence context for dirty state and executes the
SQL <code>UPDATE</code> automatically to synchronize the in-memory with the database state.
*/
tx.commit();
// UPDATE MESSAGE set TEXT = 'Take me to your leader!' where ID = 1
em.close();
}
} finally {
TM.rollback();
emf.close();
}
}
use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.
the class AuditLogging method writeAuditLog.
@Test
public void writeAuditLog() throws Throwable {
UserTransaction tx = TM.getUserTransaction();
try {
Long CURRENT_USER_ID;
{
tx.begin();
EntityManager em = JPA.createEntityManager();
User currentUser = new User("johndoe");
em.persist(currentUser);
tx.commit();
em.close();
CURRENT_USER_ID = currentUser.getId();
}
EntityManagerFactory emf = JPA.getEntityManagerFactory();
Map<String, String> properties = new HashMap<String, String>();
properties.put(org.hibernate.jpa.AvailableSettings.SESSION_INTERCEPTOR, AuditLogInterceptor.class.getName());
EntityManager em = emf.createEntityManager(properties);
Session session = em.unwrap(Session.class);
AuditLogInterceptor interceptor = (AuditLogInterceptor) ((SessionImplementor) session).getInterceptor();
interceptor.setCurrentSession(session);
interceptor.setCurrentUserId(CURRENT_USER_ID);
tx.begin();
em.joinTransaction();
Item item = new Item("Foo");
em.persist(item);
tx.commit();
em.clear();
tx.begin();
em.joinTransaction();
List<AuditLogRecord> logs = em.createQuery("select lr from AuditLogRecord lr", AuditLogRecord.class).getResultList();
assertEquals(logs.size(), 1);
assertEquals(logs.get(0).getMessage(), "insert");
assertEquals(logs.get(0).getEntityClass(), Item.class);
assertEquals(logs.get(0).getEntityId(), item.getId());
assertEquals(logs.get(0).getUserId(), CURRENT_USER_ID);
em.createQuery("delete AuditLogRecord").executeUpdate();
tx.commit();
em.clear();
tx.begin();
em.joinTransaction();
item = em.find(Item.class, item.getId());
item.setName("Bar");
tx.commit();
em.clear();
tx.begin();
em.joinTransaction();
logs = em.createQuery("select lr from AuditLogRecord lr", AuditLogRecord.class).getResultList();
assertEquals(logs.size(), 1);
assertEquals(logs.get(0).getMessage(), "update");
assertEquals(logs.get(0).getEntityClass(), Item.class);
assertEquals(logs.get(0).getEntityId(), item.getId());
assertEquals(logs.get(0).getUserId(), CURRENT_USER_ID);
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.
the class AccessJPAMetamodel method accessDynamicMetamodel.
@Test
public void accessDynamicMetamodel() throws Exception {
EntityManagerFactory entityManagerFactory = JPA.getEntityManagerFactory();
Metamodel mm = entityManagerFactory.getMetamodel();
Set<ManagedType<?>> managedTypes = mm.getManagedTypes();
assertEquals(managedTypes.size(), 1);
ManagedType itemType = managedTypes.iterator().next();
assertEquals(itemType.getPersistenceType(), Type.PersistenceType.ENTITY);
SingularAttribute nameAttribute = itemType.getSingularAttribute("name");
assertEquals(nameAttribute.getJavaType(), String.class);
assertEquals(nameAttribute.getPersistentAttributeType(), Attribute.PersistentAttributeType.BASIC);
assertFalse(// NOT NULL
nameAttribute.isOptional());
SingularAttribute auctionEndAttribute = itemType.getSingularAttribute("auctionEnd");
assertEquals(auctionEndAttribute.getJavaType(), Date.class);
assertFalse(auctionEndAttribute.isCollection());
assertFalse(auctionEndAttribute.isAssociation());
}
use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.
the class JpaApplication method main.
public static void main(String[] args) {
EntityManagerFactory factory = null;
EntityManager em = null;
EntityTransaction tx = null;
try {
factory = Persistence.createEntityManagerFactory("infinite-finances");
em = factory.createEntityManager();
tx = em.getTransaction();
tx.begin();
// select t from transaction t
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Transaction> criteriaQuery = cb.createQuery(Transaction.class);
Root<Transaction> root = criteriaQuery.from(Transaction.class);
criteriaQuery.select(root);
TypedQuery<Transaction> query = em.createQuery(criteriaQuery);
List<Transaction> transactions = query.getResultList();
for (Transaction t : transactions) {
System.out.println(t.getTitle());
}
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
em.close();
factory.close();
}
}
use of javax.persistence.EntityManagerFactory in project microservices by pwillhan.
the class MySqlApp method main.
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
try {
entityManagerFactory = Persistence.createEntityManagerFactory("test-unit");
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
CustomerJpaDao customerDao = new CustomerJpaDao();
customerDao.setEntityManager(entityManager);
Customer customer = new Customer();
customer.setName("Tom");
customer.setAge(18);
// CREATE
Customer createdCustomer = customerDao.save(customer);
System.out.println(createdCustomer.getId());
// GET one
Long customerId = createdCustomer.getId();
Customer foundCustomer = customerDao.findById(customerId);
System.out.println(foundCustomer);
// UPDATE
foundCustomer.setName("Dick");
Customer updatedCustomer = customerDao.save(foundCustomer);
System.out.println(updatedCustomer);
entityManager.getTransaction().commit();
// Native Query
nativeQuery(entityManager);
} catch (Exception e) {
entityManager.getTransaction().rollback();
} finally {
entityManager.close();
entityManagerFactory.close();
}
}
Aggregations