0

I'm trying to write a single page app which will persist the current users into a database table(HSQL) and also a list of "stories"(just 1 liners) into a separate table (in same DB)

I have 2 POJOs, User and Story. Then 2 dtos, 2 repositories etc but am struggling to figure out how to persist these to 2 tables...

Basically I need to know whether I need 2 persistence-units and 2 entityManagerFactory's , even though I wish to write to a single database, but to 2 tables...as seems to be the case from looking around but part of the problem is that I am very confused with some of the lingo.

There are many questions regarding multiple tables, but they always seem to be in different data sources. In this context are data sources simply tables? Ie persisting to same database but different tables (aka data sources) If not, are "datasource" and "database" interchangeable in this context?

Thanks.

Phil
  • 494
  • 2
  • 21

1 Answers1

0

Datasource is an abstraction of an arbitrary collection of data. In regular cases your schema could be your datasource. Datasource granularity is totally up to you but I guess more coarse grained datasources have better designs. So, you need one persistence unit and one EntityManagerFactory. In a trivial scenario, you could define your beans like this:

<bean id="datasource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:url="datasource url"
          p:username="your uname"
          p:password="your pass"
          p:driverClassName="dirver name"/>

    <bean id="persistenceProvider"
          class="org.hibernate.jpa.HibernatePersistenceProvider"/>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:packagesToScan="your model packages"
          p:dataSource-ref="datasource"
          p:persistenceProvider-ref="persistenceProvider" />
ragingasiancoder
  • 616
  • 6
  • 17
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • Okay thanks for explanation regarding Datasource. So regarding the persistence-unit, having one is fine but how do you then refer to 2 different tables? – Phil Jan 07 '15 at 14:36
  • In a traditional `four-tier` architecture, define your `models` which represents different tables, then put data access functionalities on `Data Access Layer` and combine those functionalities in `Service Layer`. Normally, Service Layer methods are `Transactional`. If you're gonna use Spring, spring documentation have done a great job on this topic. you should [check it out](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/). Also check [Spring-Data](http://projects.spring.io/spring-data-jpa/) project which provides common data access functionalities – Ali Dehghani Jan 07 '15 at 18:48