54 lines
2.2 KiB
Java
Executable File
54 lines
2.2 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.Session;
|
|
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;
|
|
|
|
/**
|
|
* A @NaturalId concept, expressed in Hibernate's native "mapping.xml" XML dialect
|
|
* (namespace http://www.hibernate.org/xsd/orm/mapping) on a class with ZERO annotations.
|
|
* The JPA-standard orm.xml dialect (orm_3_2.xsd) has no <natural-id> element -- this is a
|
|
* Hibernate-only extension that only the extended XML dialect (or Java annotations) can express.
|
|
*
|
|
* <p>Docs: docs/04-annotations-vs-xml.md, Topic 1.
|
|
*/
|
|
@SpringBootTest(classes = HibernateDemoApplication.class)
|
|
@TestPropertySource(properties = {
|
|
"spring.jpa.mapping-resources=mapping-xml-natural-id.xml"
|
|
})
|
|
class MappingXmlNaturalIdTest {
|
|
|
|
@Autowired
|
|
private EntityManagerFactory emf;
|
|
|
|
@Test
|
|
void naturalIdDefinedPurelyInXml_resolvesViaByNaturalId() {
|
|
EntityManager em = emf.createEntityManager();
|
|
em.getTransaction().begin();
|
|
MappingXmlNaturalIdEntity e = new MappingXmlNaturalIdEntity("SKU-XML-1", "XML Widget");
|
|
em.persist(e);
|
|
em.getTransaction().commit();
|
|
em.close();
|
|
|
|
EntityManager em2 = emf.createEntityManager();
|
|
Session session = em2.unwrap(Session.class);
|
|
MappingXmlNaturalIdEntity loaded = session.byNaturalId(MappingXmlNaturalIdEntity.class)
|
|
.using("sku", "SKU-XML-1")
|
|
.load();
|
|
em2.close();
|
|
|
|
assertThat(loaded).isNotNull();
|
|
assertThat(loaded.getName()).isEqualTo("XML Widget");
|
|
System.out.println("RESULT[mapping-xml-natural-id]: session.byNaturalId() resolved an entity whose "
|
|
+ "@NaturalId-equivalent was declared ENTIRELY in Hibernate's native mapping.xml dialect, "
|
|
+ "zero Java annotations. name=" + loaded.getName());
|
|
}
|
|
}
|