Question

in my project I'm mapping the DB to the class using xml(not Annotations), I have mapped two tables to one class as follow.

<hibernate-mapping>
  <class name="com.fg.fixtransbridge.model.BookStatistics"
    entity-name="BookStatistics" table="book_statistics">       
  </class>

  <class name="com.fg.fixtransbridge.model.BookStatistics"
    entity-name="BookStatisticsHistory" table="book_statistics_copy">
  </class>
</hibernate-mapping>  

And when I tries to add data to the two tables at once, only the book_statistics table gets filled. It's because I called it 1st

b is a BookStatistics instansce and it's filled with data

    session.saveOrUpdate("BookStatistics", b);
    session.saveOrUpdate("BookStatisticsHistory", b);

If i calls session.saveOrUpdate("BookStatisticsHistory", b) 1st, then only the other table get filled.

    SessionFactory sessionFactory;
    ServiceRegistry serviceRegistry;

    Configuration configuration = new Configuration();
    configuration.configure();
    serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    Session session = sessionFactory.openSession();

    session.beginTransaction();
    session.saveOrUpdate("BookStatistics", b);
    session.saveOrUpdate("BookStatisticsHistory", b);     
    session.getTransaction().commit();

So is there any way to fill those two tables using single service. Thanks in advance

Was it helpful?

Solution

You can do this by using two sessions. like,

Session session1 = sessionFactory.openSession();
Session session2 = sessionFactory.openSession();

But I think this is not very good practice. Anyway there is no need of a two tables in one DAO. That too isn't a good practise.

So I've created two DAOs for the two tables and did my CRUD (Create, Read, Update, Delete) operations there and used one service to call booth.

And for the sake of effectiveness, I Autowired the session factory. Otherwise when it tries to do any CRUD operations, It creates a new session factory every time which consumes a lot of time and resource.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top