我的 DAO 实现存在一些问题。我的场景:我在我的数据库中插入一个实体,我从我的数据库中两次获得这个实体。我了解 AssertSame 和 AssertEquals 之间的区别。我想同一个实体应该在这两种情况下都通过。在我的情况下, AssertEquals 通过,但 AssertSame 失败。
我已经为此苦苦挣扎了很长时间,任何帮助都将不胜感激。
我的问题是:必须满足哪些条件才能确保这两个实体相同?我应该在我的代码中更改什么?
我只粘贴了我认为必不可少的部分类和配置文件。
StudentEntity 类使用@Entity 进行注释。
我准备了以下 jUnit 测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/dao-context.xml", "/hibernate-context.xml", "/core-context.xml" })
public class BidirectionalTest {
@Autowired
private UserService userService;
@Test
public void testBidirectionalRelation() {
try {
StudentEntity s = new StudentEntity();
s.setLogin("Login");
userService.registerUser(s);
StudentEntity foundStudent1 = (StudentEntity) userService.findUserByLogin("Login");
StudentEntity foundStudent2 = (StudentEntity) userService.findUserByLogin("Login");
assertEquals(foundStudent1, foundStudent2);
assertSame(foundStudent1, foundStudent2); // fail!
} catch (ServiceException e) {
e.printStackTrace();
}
}
}
我的服务实现的一部分:
@Transactional(propagation=Propagation.REQUIRED)
public class UserServiceImpl implements UserService{
private UserDao userDao;
public AbstractUserEntity findUserByLogin(String login) throws ServiceException {
Long userId = getUserDao().findUserByLogin(login);
if(userId == null) {
return null;
}
return getUserDao().findUser(userId);
}
public Long registerUser(AbstractUserEntity user) throws ServiceException {
Long duplicateUserId = getUserDao().findUserByLogin(user.getLogin());
if (duplicateUserId!=null) {
throw new ServiceException("Użytkownik już istnieje");
}
return getUserDao().insertUser(user);
}
}
我的 dao 实现的一部分:
@Repository
public class HibernateUserDao implements UserDao {
private EntityManagerFactory emf;
public EntityManagerFactory getEmf() {
return emf;
}
@PersistenceUnit
public void setEmf(EntityManagerFactory emf) {
this.emf = emf;
}
@Override
public Long insertUser(AbstractUserEntity user) {
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
} finally {
if (em != null) em.close();
}
return user.getId();
}
@Override
public Long findUserByLogin(String login) {
EntityManager em = emf.createEntityManager();
Long result;
try{
result = (Long) em.createNamedQuery("findUserByLogin").setParameter("login", login).getSingleResult();
} catch(NoResultException nre) {
return null;
}
return result;
}
}
我的persistence.xml的一部分
<persistence-unit name="JpaPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
</properties>
</persistence-unit>
我的 core-context.xml 的一部分
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- a PlatformTransactionManager is still required -->
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<ref local="atomikosTM" />
</property>
<property name="userTransaction">
<ref local="atomikosUTX" />
</property>
</bean>
<bean id="atomikosTM" class="com.atomikos.icatch.jta.UserTransactionManager" />
<bean id="atomikosUTX" class="com.atomikos.icatch.jta.UserTransactionImp" />
编辑:
谢谢你的回答。现在我知道我需要一个缓存。我找到了一个很好的解释:“在 JPA 中,不跨 EntityManagers 维护对象身份。每个 EntityManager 都维护自己的持久性上下文,以及它自己的对象事务状态。” 我更改了我的 persistence.xml,但我的测试仍然失败。
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="JpaPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>amg.training.spring.model.StudentEntity</class>
<class>amg.training.spring.model.SubjectEntity</class>
<class>amg.training.spring.model.TeacherEntity</class>
<class>amg.training.spring.model.AbstractUserEntity</class>
<class>amg.training.spring.model.TeacherDegree</class>
<class>amg.training.spring.dao.AbstractEntity</class>
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
</properties>
</persistence-unit>