Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7879813
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T03:59:24+00:00 2026-06-03T03:59:24+00:00

I have some problems with my DAO implementation. My scenario: I insert one entity

  • 0

I have some problems with my DAO implementation. My scenario: I insert one entity in my database, I get this entity twice from my database. I understand difference between AssertSame and AssertEquals. I guess that the same entity should pass in both cases. In my case AssertEquals passes ,but AssertSame fails.

I have been struggling with that for a long time and any help will be greatly appreciated.

My question is: What conditions have to be met in order to be sure that these two entities are the same? What should I change in my code?

I pasted only parts of my classes and config files which I in my opinion are essential.

StudentEntity class is annotated with @Entity.

I’v prepared the following jUnit test:

@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();
        }
    }
}

Part of my service implementation:

@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);
}
}

Part of my dao implementation:

@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;
}

}

Part of my 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>

Part of my 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" />

edit:

Thx for your answers. Now I know I need a cache. I found a good explanation: “In JPA object identity is not maintained across EntityManagers. Each EntityManager maintains its own persistence context, and its own transactional state of its objects.” I changed my persistence.xml, but my test still fails.

<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>

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T03:59:25+00:00Added an answer on June 3, 2026 at 3:59 am

    Finally managed to make it work. I think that lack of cache was not a problem. It is necessary to bind a resource (in our case EntityManagerFactory ) to the same thread. link to doc of .bindResource() method

    @PersistenceUnit
    private EntityManagerFactory emf;
    private EntityManager em;
    
    @Before
    public void setUp() {
        em = emf.createEntityManager();
        TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
    }
    
    @After
    public void tearDown() {
    TransactionSynchronizationManager.unbindResource(emf);
    EntityManagerFactoryUtils.closeEntityManager(em);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some problems to pass message from background page to my content_script.js. I
Have some problems with NSIS uninstall code. RMDir /r $SMPROGRAMS\${PRODUCT_NAME} In Windows 7 this
I have some problems sending mails through SMTP using Spring's MailSender interface and the
I have some problems with OpenCV s cvCanny(...) and the Image data types it
i have some problems with rowspan: var doc1 = new Document(); doc1.SetPageSize(PageSize.A4.Rotate()); string path
I have some problems sending an id though jquery. I have a form select
I have some problems with mod_rewrited at .httacess. We have created a website, the
I have some problems to start programming using cocos2D on linux + android. I
I have some problems with controlling a while loop inside an event structure. Say
I have some problems with a java app i'm developing, i'm using HtmlCleaner 2.2

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.