|
| 1 | +package com.baeldung.hibernate.namingstrategy; |
| 2 | + |
| 3 | +import static org.junit.Assert.fail; |
| 4 | + |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.Properties; |
| 7 | + |
| 8 | +import org.hibernate.HibernateException; |
| 9 | +import org.hibernate.Session; |
| 10 | +import org.hibernate.SessionFactory; |
| 11 | +import org.hibernate.boot.MetadataSources; |
| 12 | +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; |
| 13 | +import org.hibernate.cfg.Configuration; |
| 14 | +import org.hibernate.service.ServiceRegistry; |
| 15 | +import org.junit.After; |
| 16 | +import org.junit.Before; |
| 17 | +import org.junit.Test; |
| 18 | + |
| 19 | +public class NamingStrategyLiveTest { |
| 20 | + |
| 21 | + private Session session; |
| 22 | + |
| 23 | + @Before |
| 24 | + public void init() { |
| 25 | + try { |
| 26 | + Configuration configuration = new Configuration(); |
| 27 | + |
| 28 | + Properties properties = new Properties(); |
| 29 | + properties.load(Thread.currentThread() |
| 30 | + .getContextClassLoader() |
| 31 | + .getResourceAsStream("hibernate-namingstrategy.properties")); |
| 32 | + |
| 33 | + configuration.setProperties(properties); |
| 34 | + |
| 35 | + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) |
| 36 | + .build(); |
| 37 | + MetadataSources metadataSources = new MetadataSources(serviceRegistry); |
| 38 | + metadataSources.addAnnotatedClass(Customer.class); |
| 39 | + |
| 40 | + SessionFactory factory = metadataSources.buildMetadata() |
| 41 | + .buildSessionFactory(); |
| 42 | + |
| 43 | + session = factory.openSession(); |
| 44 | + } catch (HibernateException | IOException e) { |
| 45 | + fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + @After |
| 50 | + public void close() { |
| 51 | + if (session != null) |
| 52 | + session.close(); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + public void testCustomPhysicalNamingStrategy() { |
| 57 | + |
| 58 | + Customer customer = new Customer(); |
| 59 | + customer.setFirstName("first name"); |
| 60 | + customer.setLastName("last name"); |
| 61 | + customer.setEmailAddress("customer@example.com"); |
| 62 | + |
| 63 | + session.beginTransaction(); |
| 64 | + |
| 65 | + Long id = (Long) session.save(customer); |
| 66 | + |
| 67 | + session.flush(); |
| 68 | + session.clear(); |
| 69 | + |
| 70 | + Object[] result = (Object[]) session.createNativeQuery("select c.first_name, c.last_name, c.email from customers c where c.id = :id") |
| 71 | + .setParameter("id", id) |
| 72 | + .getSingleResult(); |
| 73 | + |
| 74 | + } |
| 75 | +} |
0 commit comments