I use entity beans and some Stateless ejb that provide my HomeLocal and HomeRemote interface, where I inject persistenceContext and obtain EntityManager.
As new requirement (migration on Karaf) I have to get rid of all EJB.
My question is how can I replace this stateless ejb with simple DAO classes and inject or obtain Entity manager in these classes?
My JPA provider is hibernate.
I need some example, tutorials or any kind of help.
You could use the Apache Aries project:
Amusing you will be using blueprint, declare your bean and define a service (assuming you want to use services)
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0">
<bean id="jpaDemo" init-method="init" class="org.demo.osgi.datasource.jpa.JpaComponentImpl">
<jpa:context unitname="demo" property="entityManager"/>
<tx:transaction method="*" value="Required"/>
</bean>
<service ref="jpaDemo" interface="org.demo.osgi.datasource.jpa.JpaComponent"/>
</blueprint>
The JpaComponent can then use the injected entityManager (code in Scala, but i'm sure you'll get the idea)
trait JpaComponent {
}
class JpaComponentImpl extends JpaComponent {
val logger = org.slf4j.LoggerFactory.getLogger(classOf[JpaComponent])
#BeanProperty
var entityManager : EntityManager = _
def init = {
logger.info(s"em=${entityManager}")
}
}
Place a persistence.xml in your bundle (e.g, META-INF/persistence.xml). Sample below:
<persistence-unit name="demo" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/jbtravel)</jta-data-source>
<mapping-file>META-INF/airport.xml</mapping-file>
</persistence-unit>
You will need the following features:
jpa
hibernate
jndi
transaction
And the following bundles
mvn:org.apache.aries/org.apache.aries.util/1.0.1
mvn:org.apache.aries.jpa/org.apache.aries.jpa.api/1.0.1
mvn:org.apache.aries.jpa/org.apache.aries.jpa.container.context/1.0.1
Plus set the following OSGI meta-data
Meta-Persistence: META-INF/persistence.xml
Service-Component: *
See also https://github.com/rparree/osgi-demos/tree/master/datasource for the sample from above
Related
I'm learning spring dependency injection with Struts2, beased on a web project. In my example, I created a zoo having animals. Animal will talk if injection is succeed. E.g. in the console, we will see dog's talk :
Wowowo ฅ^•ﻌ•^ฅ
However, if injection failed, then we'll see :
zooService bean has not been injected.
Here's the architecture of my application :
com.zoo.controller.ZooController is the controller for receiving web actions.
com.zoo.service.ZooService is the interface for animal's talk
com.zoo.service.ZooServiceForDog is the implementation for dog's talk
Problem
Up to the step, everything is OK. And the dependency injection is handled by Spring using an XML file called applicationContext.xml. However, I've 2 types of configuration for this file, the first one Config 1 works but the second Config 2 doesn't.
Injection succeed using config 1.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="zooService" class="com.zoo.service.ZooServiceForDog" />
</beans>
Injection failed using config 2.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="zooController" class="com.zoo.controller.ZooController">
<property name="zooService" ref="zooServiceBean" />
</bean>
<bean id="zooServiceBean" class="com.zoo.service.ZooServiceForDog" />
</beans>
Can somebody explain why the Config 2 cannot work ?
Here're other codes that might be helpful to the issue :
Class com.zoo.controller.ZooController:
package com.zoo.controller;
import com.zoo.service.ZooService;
import com.opensymphony.xwork2.ActionSupport;
public class ZooController extends ActionSupport {
private static final long serialVersionUID = 1L;
private ZooService zooService;
public String live () {
if (zooService != null) {
zooService.talk();
} else {
System.out.println("zooService bean has not been injected.");
}
return SUCCESS;
}
public ZooService getZooService() {
return zooService;
}
public void setZooService(ZooService zooService) {
this.zooService = zooService;
}
}
It cannot work because the scope of the zooController is singleton. You should make the scope prototype.
<bean id="zooController" class="com.zoo.controller.ZooController" scope="prototype" >
<property name="zooService" ref="zooServiceBean" />
</bean>
The dependency management is defined by the container:
If your actions managed by Struts container, then Struts is creating them in the default scope. If your actions is managed by Spring container then you need to define the scope of the action beans, because Spring by default uses singleton scope and if you don't want to share your action beans between user's requests you should define the corresponding scope. You can use prototype scope, which means a new instance is returned by the Spring each time Struts is being built an action instance.
The Struts integrates to Spring via plugin. Make sure it has
<constant name="struts.objectFactory" value="spring" />
then you can delegate actions to Spring
References:
Struts2 and Spring
Spring plugin
EDIT:
In your first config you declared a bean zooService that will be injected by Struts using spring object factory.
In your second config you declared two beans zooController and zooServiceBean, but you changed the name of the second bean. Then you tried to build the action bean using spring object factory like in the first case. And because there's no bean with name zooService the autowiring has been failed. Because by default Struts is configured to autowire beans from the application context by name.
Then you changed struts.xml and used a bean reference in the action class attribute. It means that Struts will use app context to get a bean from Spring. And because it has an explicit dependency on the second bean, it would be wired before the bean is returned.
com.service.EmployeeService has method create createEmployee which calls method under dao class i.e com.dao.EmployeeDao(having EntityManager as dependency).
Now i want to make method createEmployee transactional with #Transactional. Is it mandatoty to declare the package com.service
under packagesToScan in spring config file ?
I mean is it mandatory to declare the package of class using #Transactional under packagesToScan to make it work ?
FYI I referred the how-does-spring-transactional-really-work to understand how spring transactions works internally
#Transactional is used on a class or method for the transaction management whereas packagesToScan is used by spring for scanning annotations on your entity classes
<property name="packagesToScan">
<list>
<value>com.xyz.EntityName</value>
</list>
</property>
I used #Transactional on my DaoImpl methods(CRUD) and used packagesToScan on the entities for spring to pick.
When you use spring with hibernate it is the responsibility of the spring's class i.e org.springframework.orm.hibernate4.LocalSessionFactoryBean
as in <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
instead of Hibernate's new Configuration().configure().buildSessionFactory()
Moreover in hibernate you use to tell hibernate to consider the entities which are using annotation as in hibrnate.cfg.xml by using
<mapping class="com.hiber.hr.Countries"/>
<mapping class="com.hiber.hr.Departments"/>
Similarly you need to tell spring the same through packagesToScan property.
Internally Spring calls the Hibernate's addAnnotatedClass method of org.hibernate.cfg.Configuration class
Hibernate method called from Spring:-
public Configuration addAnnotatedClass(Class annotatedClass)
{
XClass xClass = reflectionManager.toXClass(annotatedClass);
metadataSourceQueue.add(xClass);
return this;
}
Transactional makes a Spring bean method transactional.
packagesToScan is a property of the Spring sessionFactory / entityManagerFactory beans, that tell them where to find JPA entities.
They are completely orthogonal. Entities are not Spring beans. And transactional Spring beans are not entities that must be found by the SessionFactory / EntityManagerFactory.
I am new to JPA and developing a webapp(J2EE) where the webapp is in Tomcat so I can't use #PersistenceContext. I decided to use a Helper class and everything was going fine. Then I decided to implement JNDI for connection pooling and I managed to get Datasource.
The Helper Class looks like the following:
try {
Context initCtx = new InitialContext();
entityManager = //class cast exception
(EntityManager)initCtx.lookup(
"java:/comp/env/jdbc/LCDS"
);
DataSource ds= (DataSource)initCtx.lookup(
"java:/comp/env/jdbc/LCDS"
);
System.out.println(ds.getConnection()+"Cool");
//jdbc:mysql://localhost:3306/XXXXXXX, UserName=root#localhost, MySQL-AB JDBC DriverCool
emf=(EntityManagerFactory) source.getConnection(); //class cast exception
emf = Persistence.createEntityManagerFactory("XXXX"); //working version
}
The error is:
ava.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to javax.persistence.EntityManager
I don't know where I am getting wrong. I am not able to get EntityManagerFactory or EntityManager via JNDI lookup. I tried #Resource(name="jdbc/LCDS") and #PersistenceUnit(name="jdbc/LCDS").
To use a JNDI datasource in JPA, this should be specified in the persistence.xml, something like:
<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">
<persistence-unit name="..." transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:/comp/env/jdbc/LCDS</non-jta-data-source>
...
Then you just have to create your EntityManagerFactory via Persistence#createEntityManagerFactory(String). If you want to recycle the EntityManagerFactory, this should be done outside of JNDI (e.g. as a ServletContext attribute). This is because Tomcat is not a Java EE server, only a servlet container: he is not able to inject the persistence unit.
UPDATE
JNDI access to persistence unit is not possible due to Tomcat limitations. See JPA Tomcat limitations. You will have to use emf = Persistence.createEntityManagerFactory("UNIT NAME").
Sorry for misleading answer. I've tested that on WebSphere Liberty, didn't have Tomcat at hand.
If you need that functionality check WebSphere Liberty, which is as fast and lightweight as Tomcat, but is fully Java EE Web profile compliant. It has lots of useful features like JPA, EJBLite, JAX-RS already available if needed, without fighting with additional libraries configuration.
UPDATE END
I've checked on WebSphere Liberty, you need to create reference to lookup your persistence unit via JNDI. You have two options to create that:
Use annotation at the class level
In any of your servlets you need to define annotation using the follownig:
#PersistenceUnit(name="JPATestRef", unitName="UnitName")
public class JPATester extends HttpServlet {
...
Use entry in web.xml
<persistence-unit-ref>
<persistence-unit-ref-name>JPATestRef</persistence-unit-ref-name>
<persistence-unit-name>UnitName</persistence-unit-name>
</persistence-unit-ref>
Then you access it using the following code:
try {
InitialContext ctx = new InitialContext();
System.out.println("looking EntityManagerFactory:");
EntityManagerFactory emf2 = (EntityManagerFactory) ctx.lookup("java:comp/env/JPATestRef");
System.out.println("emf:2" + emf2);
} catch (NamingException e) {
I'm trying to develop a simple JSP based web application with JPA and would like to know the correct usage for developing one.
In my sample application I have two JSP pages and a simple Java class to perform database operations. Both the JSP files use this Java class to perform DB operations.
I've annotated this class with #Stateless and injected an Entity manager as follows:
#PersistenceContext(unitName = "myjpa")
EntityManager em;
In my persistence.xml I've set the following property:
<property
name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"
/>
I'm calling the class in JSP using JNDI (as the class is annotated for a stateless session bean) as follows:
InitialContext ic = new InitialContext();
Sample sample = (Sample) ic.lookup("java:app/" + application.getContextPath() + "/Sample");
I'm facing the following scenarios:
When I try to use a transaction em.getTransaction().begin()/commit() for insert and update, it says can not use transaction with JTA case.
So in the constructor code of my Java class I use the following code:
Properties properties = new Properties();
properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
emf = Persistence.createEntityManagerFactory("myjpa",properties);
em = emf.createEntityManager();
I tried to use transactions like em.getTransaction().begin()/commit().
But in this case the pages become very slow after 2-3 database update and load operations. Though I'm not getting any exception. Overall in my table I'm having less than 25 records.
To me it seems as if it is waiting internally for some operation to complete.
At the same time I also feel that the way I'm using JPA is wrong and hence soliciting advice for the correct approach for doing even simple web apps with JSP and JPA.
While I'm still exploring Java EE, in case you have any specific reference for such cases I'll like to read and look them too.
You should always strive to use JTA transactions which means the container will handle the transaction demarcations. In your case if you want to handle transactions by your self, you need to define it as a bean managed transaction. So in your EJB class, after the #Stateless annoattions, you should define the following annotation;
#TransactionManagement(TransactionManagementType.BEAN)
The usual best practice is to let the container handle the transactions, unless there is some explicit reason for you to use Bean managed transactions.
At the same time I also feel that the way I'm using JPA is wrong
Your usage indeed seems wrong. If you're using a (stateless) session bean you do not have to fiddle with em.getTransaction().begin()/commit() and you definitely don't have to use code such as Persistence.createEntityManagerFactory.
You also don't have to set the property org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform.
A session bean automatically manages the transaction for you, and within a Java EE AS (such as JBoss AS) you don't have to configure any transaction manager or similar things.
An example:
#Stateless
public class UserDAO {
#PersistenceContext
private EntityManager entityManager;
public void add(User user) {
entityManager.persist(user);
}
}
As for the persistence.xml file, something like the following should be enough to get started:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
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">
<persistence-unit name="somePU">
<jta-data-source>java:app/someDS</jta-data-source>
</persistence-unit>
</persistence>
Some more examples:
http://jdevelopment.nl/sample-crud-app-with-jsf-and-richfaces
http://arjan-tijms.omnifaces.org/2011/08/minimal-3-tier-java-ee-app-without-any.html
I have an application using Java servlets/JSP's. There are multiple clients using my app, however each client has a separate database. All the databases have the same schema. I would like to determine which database connection to use at the time when a user logs into the system.
For example client A logs in, I determine that client A belongs to database C, grab the connection for database C and continue on my merry way.
I am using JPA with Hibernate as my JPA provider. Is it possible to do this using multiple persistence units and determining which unit to use at login time? Is there a better/preferred way to do this?
Edited to add:
I am using annotations and EJB's so the Persistence Context is being set in the EJB with #PersistenceContext(unitName = "blahblah"), can this be determined at login time? Can I change the unitName at runtime?
Thanks
1) Create several persistent units in your persistence.xml with different names.
2) Create necessary number of EntityManagerFactorys (1 per persistence-unit) and specify which persistence-unit should be used for concrete factory:
<bean id="authEntityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SpringSecurityManager"/>
</bean>
3) Create necessary number of TransactionManager s:
<bean id="authTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="authEntityManagerFactory" />
</bean>
4) In your DAO's classes specify with which persistence-unit (and so with which EntityManagerFactory) you want to work:
public class AbstractAuthDao<T> {
#PersistenceContext (unitName = "SpringSecurityManager")
protected EntityManager em;
...
}
5) In your service-objects specify which TransactionManager should be used (this feature is supported only in Spring 3.0):
#Transactional (value = "authTransactionManager", readOnly = true)
public class UserServiceImpl implements UserService {
...
}
6) If you have OpenEntityManagerInViewFilter in your web.xml, then specify in its init-param name of necessary EntityManagerFactory (or create several filters with correspondent init-blocks):
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>authEntityManagerFactory</param-value>
</init-param>