59 lines
2.5 KiB
Java
Executable File
59 lines
2.5 KiB
Java
Executable File
package com.ankurm.hibernatedemo.mappingstyle;
|
|
|
|
import static org.assertj.core.api.Assertions.assertThat;
|
|
|
|
import com.ankurm.hibernatedemo.HibernateDemoApplication;
|
|
import jakarta.persistence.EntityManager;
|
|
import jakarta.persistence.EntityManagerFactory;
|
|
import org.hibernate.SessionFactory;
|
|
import org.hibernate.engine.spi.SessionFactoryImplementor;
|
|
import org.hibernate.persister.entity.EntityPersister;
|
|
import org.junit.jupiter.api.Test;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.boot.test.context.SpringBootTest;
|
|
import org.springframework.test.context.TestPropertySource;
|
|
|
|
/**
|
|
* The entity's field is annotated {@code @Column(name = "annotation_name")}. The matching
|
|
* orm.xml entry maps the same field to {@code xml_name}. This test reads back the ACTUAL
|
|
* column name Hibernate used, straight from the runtime metamodel and from the real DDL/SQL,
|
|
* to settle who wins.
|
|
*
|
|
* <p>Docs: docs/04-annotations-vs-xml.md, Topic 1.
|
|
*/
|
|
@SpringBootTest(classes = HibernateDemoApplication.class)
|
|
@TestPropertySource(properties = {
|
|
"spring.jpa.mapping-resources=orm-xml-override-mapping.xml"
|
|
})
|
|
class AnnotationXmlOverrideTest {
|
|
|
|
@Autowired
|
|
private EntityManagerFactory emf;
|
|
|
|
@Test
|
|
void xmlColumnMapping_winsOverAnnotationColumnMapping() {
|
|
SessionFactoryImplementor sfi = emf.unwrap(SessionFactoryImplementor.class);
|
|
EntityPersister persister = sfi.getMappingMetamodel()
|
|
.getEntityDescriptor(OverrideEntity.class);
|
|
String[] columnNames = persister.getPropertyColumnNames("value");
|
|
System.out.println("RESULT[override]: runtime column name for OverrideEntity.value = " + columnNames[0]
|
|
+ " (annotation said 'annotation_name', orm.xml said 'xml_name')");
|
|
assertThat(columnNames).containsExactly("xml_name");
|
|
|
|
// Prove it end-to-end: actually persist and read the row back through the winning column.
|
|
EntityManager em = emf.createEntityManager();
|
|
em.getTransaction().begin();
|
|
OverrideEntity e = new OverrideEntity("hello");
|
|
em.persist(e);
|
|
em.getTransaction().commit();
|
|
em.close();
|
|
|
|
EntityManager em2 = emf.createEntityManager();
|
|
Object row = em2.createNativeQuery("select xml_name from override_entity where id = " + e.getId())
|
|
.getSingleResult();
|
|
em2.close();
|
|
assertThat(row).isEqualTo("hello");
|
|
System.out.println("RESULT[override]: native query against column 'xml_name' returned: " + row);
|
|
}
|
|
}
|