users@glassfish.java.net

Re: Creating EntityManager with a specific username and password?

From: <glassfish_at_javadesktop.org>
Date: Sun, 04 Jan 2009 06:27:10 PST

Hi,

I have found the way how to connect to DB via bean managed and resource local entity manager. However it is persistence provider specific and non standardized approach. Here is mine persistence.xml fragment:

<persistence-unit name="userResourceLocal" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
                <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
                <property name="hibernate.connection.driver_class" value="net.sourceforge.jtds.jdbc.Driver"/>
                <property name="hibernate.connection.url" value="jdbc:jtds:sqlserver://host/Db"/>
                <property name="hibernate.connection.username" value="username"/>
                <property name="hibernate.connection.password" value="changeit"/>
        </properties>
</persistence-unit>

I think, similar persistence unit, which serves can be made also for TopLink and appropriate DB driver. Within your application, connection can be made as follows:

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("userResourceLocal", new HashMap<String, String>() {
        private static final long serialVersionUID = 1L;
        {
                put("hibernate.connection.username", "user2");
                put("hibernate.connection.password", "password2");
        }
} );
EntityManager entityManager = entityManagerFactory.createEntityManager();

The entity manager is resource local (without XA transaction i.e. entityManager .beginTransaction() doesn't return UserTransaction but EntityTransaction) and bean managed (not automatically managed by container, i.e. all transaction specific tasks must be made manually).
[Message sent by forum member 'cigorin' (cigorin)]

http://forums.java.net/jive/thread.jspa?messageID=323977