Thursday, June 3, 2010

Configure JPA during run time, dynamic JPA Configuration using Spring context

You can set the database information during run time. Then remove all the database specific stuff
from persistance.xml and use Hash properties in your java class.

1. Removed all your database properties from persistance.xml
<persistence>
<persistence-unit name="jpablogPUnit" transaction-type="RESOURCE_LOCAL">
<class>com.suman.Company</class>
</persistence-unit>
</persistence>

2. Changed your java file where you are configuring entityManager, in our case TestApplication.java


package com.suman;

import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;

/**
* @author Binod Suman
*/
public class TestApplication {

Logger log = Logger.getLogger(TestApplication.class);
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.saveCompany();
}

public void saveCompany(){
log.info("Company data is going to save");
EntityManagerFactory emf;
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}

}

Now run the application.
One more record has been inserted.

How to fetch data using JPA

Change the code of TestApplcation.java

package com.suman;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.log4j.Logger;

/**
* @author Binod Suman
*/
public class TestApplication {

Logger log = Logger.getLogger(TestApplication.class);
EntityManagerFactory emf;
EntityManager em;

public static void main(String[] args) {
TestApplication test = new TestApplication();
test.configureEntityManager();
// test.saveCompany();
test.fetchCompanyData();
}

public void configureEntityManager(){
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
em = emf.createEntityManager();
}

public void saveCompany(){
log.info("Company data is going to save");
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}

public void fetchCompanyData(){
Query query = em.createQuery("SELECT c FROM Company c");
List<Company> list = (List<Company>) query.getResultList();
log.info(list);

for (Company company : list) {
log.info("Company Name :: "+company.getName());
log.info("Company City :: "+company.getCity());
log.info("***************************");
}
}
}


You can configure the EntityManagerFactory from spring configuration file also.

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
lazy-init="false">
<property name="persistenceUnitName" value="VMSPersistenceUnit" />
<property name="dataSource" ref="sourceDataSource" />
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>

If you want to configure entityManagerFactory during runt time then use these code. As if you dont have database name and information then you can not use the spring context for entityManagerFactory.


private EntityManagerFactory entityManagerFactory;
private JpaTemplate jpaTemplate;


LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(sourceDataSource);
bean.afterPropertiesSet();
entityManagerFactory = bean.getObject();
log.info("entityManagerFactory :: " + entityManagerFactory);
this.jpaTemplate = new JpaTemplate(this.entityManagerFactory);

Even you can fetch record in batch wise manner also.
Use this below code:
public Collection fetchQueryListFromSourceDatabaseForSubscriber(final String sql,final int firstPosition, final int numberOfRecords) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
query.setFirstResult(firstPosition);
query.setMaxResults(numberOfRecords);
List result = query.getResultList();
return result;
}
});
}

If will fetch record from firstPosition and number of record will be numberOfRecords.
A persistence provider may or may not optimize access to database using database specific limit clause, like select * from table limit 10,

Then in TestApplication.java

public Collection fetchQueryListFromSourceDatabase(final String sql) throws DataAccessException {
return (Collection) this.jpaTemplate.execute(new JpaCallback() {
public Object doInJpa(EntityManager em) throws PersistenceException {
Query query = em.createQuery(sql);
List result = query.getResultList();
log.info("FINALLY JPA WORKING :: "+result.size());
return result;
}
});
}

Please feedback to improve this tutorial ....... :)

Thanks :)

26 comments:

  1. Hello Ayush,

    I don't know why but i cant configure my System on the Fly. I open the persistence.xml and Comment the whole configuration. Then i created a HashMap with an equal configuration, but it doesn't work. It says that i have to set an Dialect if i don't have an connection.

    Do you have a hint where the problem can be?

    best regards

    Niko

    ReplyDelete
  2. This nice.How about this
    props.put(PersistenceUnitProperties.JDBC_USER, "user-name");
    props.put(PersistenceUnitProperties.JDBC_PASSWORD, "password");

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu-name", props);

    ReplyDelete
  3. This is very interesting, Үou are a very skilleԁ blogger.
    I've joined your rss feed and look forward to seeking more of your excellent post. Also, I have shared your website in my social networks!

    Also visit my web site scootertechno.com

    ReplyDelete
  4. What а stuff оf un-аmbiguіty anԁ pгеseгvеness
    of prесіouѕ know-how аbοut unexpectеd emotіons.


    Ϻy web pagе :: www. offersdailyus.com

    ReplyDelete
  5. I am truly glad tο rеad this wеbsіte рosts whiсh cοntains tоns of helpful data, thankѕ fοr pгovіding
    ѕuch іnfoгmation.

    Αlso vіsit my ωeb blog best deals for sky
    My web site - Master104Finance.com

    ReplyDelete
  6. Aω, thiѕ ωas a really good post. Tаking thе time аnd aсtual еffort tο crеate a
    really good аrtісle… but what can I
    say… I hеsitate a lot and nеver
    seem to get nearly anything done.

    Herе is my web ѕite card sharing servers cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing| cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing| cccam server|server cardsharing|skybox f3 cardsharing|cccam|cardsharing anbieter|cccam pay server|cccam server premium|dreambox|server dreambox|buy cardsharing|cardsharing|cardsharing server|dreambox 800|free card sharing server|satellite cardsharing kings|test line cccam|card sharing|card sharing servers|cardsharing canalsat|cccam line|cccam test line|free cccam server|sat keys|satellite cardsharing|

    ReplyDelete
  7. Wonderful work! Thаt is the tуpe of infоrmation thаt
    arе supposed to be ѕhared acrοss the net.
    Disgгace on Google for not positioning thiѕ poѕt higher!
    Come on over and discuss with my web ѕite . Thank you =)

    Taκе a looκ at my pаge; cccam for test

    ReplyDelete
  8. Hi there! I know this is somewhat off topic
    but I was wondering which blog platform are you using for this website?
    I'm getting tired of Wordpress because I've had
    issues with hackers and I'm looking at options for another platform. I would be great if you could point me in the direction of a good platform.

    Here is my web blog; Buy Cardsharing Cccam Server|Server Cardsharing|Skybox F3 Cardsharing|Cccam|Cardsharing Anbieter|Cccam Pay Server|Cccam Server Premium|Dreambox|Server Dreambox|Buy Cardsharing|Cardsharing|Cardsharing Server|Dreambox 800|Free Card Sharing Server|Satellite Cardsharing Kings|Test Line Cccam|Card Sharing|Card Sharing Servers|Cardsharing Canalsat|Cccam Line|Cccam Test Line|Free Cccam Server|Sat Keys|Satellite Cardsharing| Cccam Server|Server Cardsharing|Skybox F3 Cardsharing|Cccam|Cardsharing Anbieter|Cccam Pay Server|Cccam Server Premium|Dreambox|Server Dreambox|Buy Cardsharing|Cardsharing|Cardsharing Server|Dreambox 800|Free Card Sharing Server|Satellite Cardsharing Kings|Test Line Cccam|Card Sharing|Card Sharing Servers|Cardsharing Canalsat|Cccam Line|Cccam Test Line|Free Cccam Server|Sat Keys|Satellite Cardsharing| Cccam Server|Server Cardsharing|Skybox F3 Cardsharing|Cccam|Cardsharing Anbieter|Cccam Pay Server|Cccam Server Premium|Dreambox|Server Dreambox|Buy Cardsharing|Cardsharing|Cardsharing Server|Dreambox 800|Free Card Sharing Server|Satellite Cardsharing Kings|Test Line Cccam|Card Sharing|Card Sharing Servers|Cardsharing Canalsat|Cccam Line|Cccam Test Line|Free Cccam Server|Sat Keys|Satellite Cardsharing|

    ReplyDelete
  9. I'm gone to tell my little brother, that he should also go to see this blog on regular basis to take updated from most recent information.

    Feel free to surf to my homepage :: Sky Deutschland cardshaing

    ReplyDelete
  10. It is the best time to make some plans for the future and it's time to be happy. I've read this post and if I could I wish to suggest you few interesting things or advice.

    Maybe you can write next articles referring to this article.
    I want to read more things about it!

    Feel free to surf to my webpage: Satellite Cardshare CCCamserver

    ReplyDelete
  11. I do believe all the ideas you've introduced to your post. They're really convincing and can definitely work.
    Still, the posts are very short for starters. May just
    you please prolong them a bit from next time? Thanks for the post.



    Here is my webpage - http://www.officielabercrombiebe.com/

    ReplyDelete
  12. Write more, thats all I have to say. Literally, it seems as though you
    relied on the video to make your point. You obviously
    know what youre talking about, why waste
    your intelligence on just posting videos to your blog when you could be giving
    us something informative to read?

    Also visit my web page; Sidney Crosby Jersey

    ReplyDelete
  13. Wonderful website. Lots of helpful info here. I'm sending it to some friends ans additionally sharing in delicious. And certainly, thank you for your sweat!

    Feel free to visit my website - Converse Basse

    ReplyDelete
  14. I've been browsing online more than 4 hours today, yet I never found any interesting article like yours. It's pretty worth enough for me.

    Personally, if all webmasters and bloggers made
    good content as you did, the internet will
    be much more useful than ever before.

    Look into my page: Cheap NFL Jerseys

    ReplyDelete
  15. Unquestionably believe that which you stated. Your favorite reason appeared to be on the web the
    simplest thing to be aware of. I say to you, I definitely get annoyed while
    people think about worries that they just do not know about.
    You managed to hit the nail upon the top and also defined out the whole thing
    without having side effect , people can take a signal.
    Will probably be back to get more. Thanks

    Feel free to surf to my blog Michael Kors Handbags

    ReplyDelete
  16. We're a gaggle of volunteers and opening a brand new scheme in our community. Your web site offered us with valuable info to work on. You have performed an impressive activity and our entire community might be thankful to you.

    my web blog; Chaussure Air Jordan

    ReplyDelete
  17. You should be a part of a contest for one of the best blogs online.
    I am going to recommend this site!

    Also visit my blog :: Evgeni Malkin Black Jersey

    ReplyDelete
  18. You made some good points there. I looked on the net to
    find out more about the issue and found most people will go along with your views
    on this website.

    Here is my website ... Louis Vuitton Bags

    ReplyDelete
  19. Excellent post however , I was wanting to know if you could
    write a litte more on this subject? I'd be very grateful if you could elaborate a little bit more. Cheers!

    My web blog; Wholesale Jerseys

    ReplyDelete
  20. I'm impressed, I must say. Seldom do I come across a blog that's both equally educative
    and engaging, and without a doubt, you have hit
    the nail on the head. The problem is something
    too few folks are speaking intelligently about. Now i'm very happy I came across this in my search for something relating to this.

    Feel free to surf to my web blog - Abercrombie and Fitch

    ReplyDelete
  21. replica bags aaa quality gucci fake t2s26f2f86 replica bags australia check it out k1a21f4l12 replica louis vuitton bags replica bags manila e7m25i0c20 web link t2d71x7x05 replica bags china zeal replica bags

    ReplyDelete
  22. Leg warmers are belted just below the knee and flare out in shearlings and knits. Street style in Taipei has moved on from prints and color; as in Seoul, the head-to-toe monochromatic looks in neutrals dominated the scene. It's so nice when you find your true self and you stay true to that, Browne said before the show. You could accessorize your 'fits with some soft Amiri Shirts toned scarves and furs, or do it the Italian way Alexander McQueen Shoes and wear a rainbow of shades in a single look. I used to live in the center of Kyiv, but when the war began I left my flat to stay at my mother's apartment on the outskirts of the city. Of course, we had thoughts about whether we should leave Ukraine or at least move from the city, but I just felt that we needed to stay; we needed to be here. An internal audit revealed that he was losing tens of thousands Golden Goose Outlet of dollars on fabric that ended up on the cutting room floor that's tens of thousands of dollars per dress style. For fall, he has created his New York iest version yet, letting a little air in via boxy long jackets with repp Nike x Off-White stripe piping, straight leg cuffed trousers, and voluminous pleated skirts. A new shoe collab has arrived just in time for spring from L.A.-based label Simon Miller and Brazilian accessories brand Melissa. A man in search of transformation and Off White Sneakers metamorphosis; a new modern heroism. Our vision is challenging the traditional stereotypes of masculinity, empowering you to transform to find the courage to embrace who you truly are. Featuring a positive and heroic lead, the campaign sees man and horse mirror each other in their movements, Nike x Travis Scott Sneakers pushing their physical limits to transform into a mythical creature - a metaphor for personal transformation.

    ReplyDelete