Using JPA(Hibernate) with a Spring test, I was able to show that it is possible.
Assuming this is your rather enlightened entity:
models.so.haum.IntropectiveEntity.java
@Entity
public class IntrospectiveEntity {
@Transient
private EntityManager em;
protected IntrospectiveEntity() { }
public IntrospectiveEntity(final EntityManager em) {
this.em = em;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public void create() {
em.persist(this);
}
public List<IntrospectiveEntity> all() {
TypedQuery<IntrospectiveEntity> query = em.createQuery("SELECT ie FROM IntrospectiveEntity ie", IntrospectiveEntity.class);
return query.getResultList();
}
}
note that you must mark your EntityManager
as @Transient
otherwise JPA will try map it as a column. Also note that I couldn't get the EntityManager
instance injected, so had to pass that as a constructor arg.
and this is your test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class IntrospectiveEntityTest {
@PersistenceContext
private EntityManager em;
@Test
@Transactional
public void namaste() {
IntrospectiveEntity introspectiveEntity = new IntrospectiveEntity(em);
introspectiveEntity.create();
assertThat(introspectiveEntity.all().size(), IsEqual.equalTo(1));
}
@Configuration
@ComponentScan(basePackages = "so")
static class IntrospectiveEntityConfiguration {
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManager(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setPackagesToScan("so.models.haum");
return entityManagerFactory;
}
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase dataSource = builder.setType(EmbeddedDatabaseType.H2).build();
return dataSource;
}
}
}
it successfully passes. Persisting and finding itself.
So if you really want to do it this way, it is possible. Obviously the EntityManager
not being injected is probably not what you wanted but there you have it.