I am just getting started with EJB development, so I created a test system that consists of the following three projects:
Actually, the HelloWorldBeanRemote interface does also exist in the EJBTest project. I haven't found a way to import it from the other project without runtime exceptions.
The EJBTestInterfaces is a plain java project that contains only the remote interface. EJBTest contains the program logic. HelloWorldBean is a session bean. Its constructor sets the created field to the current time. In the sayHello() method it uses an injected PersistenceManager to retrieve the TestEntity with id 0 (or creates it if it does not exist), increments the ´hit` variable and returns it:
#PersistenceContext(name="manager1")
private EntityManager em;
#Override
public String sayHello() {
String info;
if (em == null)
info = "Entity Manager is null";
else {
TestEntity entity;
try {
entity = em.find(TestEntity.class, 0);
entity.setHits(entity.getHits() + 1);
em.merge(entity);
info = "Hit entity " + entity.getHits() + " times.";
} catch(Exception x) {
entity = new TestEntity();
em.persist(entity);
info = "Never used entity bean before.";
}
}
return "Hello! I was created at " + created.toString() + "<br>" + info;
}
The persistence unit is defined in the persistence.xml as follows:
<persistence>
<persistence-unit name="manager1">
<jta-data-source>java:jboss/datasources/AppointmentDS</jta-data-source>
<jar-file>../EJBTest.jar</jar-file>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<!-- also tried value="validate" -->
</properties>
</persistence-unit>
</persistence>
It uses an embedded database defined in the standalone.xml:
<datasource jndi-name="java:jboss/datasources/AppointmentDS" pool-name="AppointmentDS" enabled="true" use-java-context="true">
<connection-url>jdbc:h2:file:[path to file]</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>
The servlet basically outputs the return value of sayHello():
doGet(...) {
//get initial context ...
bean = (HelloWorldBeanRemote)initialContext.lookup(name);
output.write(bean.sayHello());
}
If I now call the servlet via a web browser, I get the expected output: The creation date and "Never used entity bean before." If I refresh the page, the creation date does not change, but the hit count increments. I can restart the servlet project without changing this behaviour. The hit count increments steadily.
However, if I restart the EJB project, everything is reset to zero. It is the expected behaviour for the creation date, but the hit count should be read from the database. But it is not.
I can see the created database files in the specified directory and they seem to contain data (I just opened the file in a text editor).
Am I supposed to use the session bean the way I did? I am not sure if I have to close the bean after the request (so the transaction can commit).
How can I make the EJB project read persisted data from the database file?
You need to change hibernate.hbm2ddl.auto value from create-drop to validate or some other value. create-drop will delete whole schema when the SessionFactory is closed and recreate it again on open.
It might be that H2 resets the DB once you restart your EJB project, that is, when the last connection is gone.
Stop your EJB project and connect to the DB to see if the expected data is still there.
Related
I am trying to migrate an application from EJB3 + JTA + JPA (EclipseLink). Currently, this application makes use of application managed persistent context due to an unknown number of databases on design time.
The application managed persistent context allows us to control how to create EntityManager (e.g. supply different datasources JNDI to create proper EntityManager for specific DB on runtime).
E.g.
Map properties = new HashMap();
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "JTA");
//the datasource JNDI is by configuration and without prior knowledge about the number of databases
//currently, DB JNDI are stored in a externalized file
//the datasource is setup by operation team
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, "datasource-jndi");
properties.put(PersistenceUnitProperties.CACHE_SHARED_DEFAULT, "false");
properties.put(PersistenceUnitProperties.SESSION_NAME, "xxx");
//create the proper EntityManager for connect to database decided on runtime
EntityManager em = Persistence.createEntityManagerFactory("PU1", properties).createEntityManager();
//query or update DB
em.persist(entity);
em.createQuery(...).executeUpdate();
When deployed in a EJB container (e.g. WebLogic), with proper TransactionAttribute (e.g. TransactionAttributeType.REQUIRED), the container will take care of the transaction start/end/rollback.
Now, I am trying to migrate this application to Spring Boot.
The problem I encounter is that there is no transaction started even after I annotate the method with #Transactional(propagation = Propagation.REQUIRED).
The Spring application is packed as an executable JAR file and run with embadded Tomcat.
When I try to execute those update APIs, e.g. EntityManager.persist(..), EclipseLink always complains about:
javax.persistence.TransactionRequiredException: 'No transaction is currently active'
Sample code below:
//for data persistence
#Service
class DynamicServiceImpl implements DynamicService {
//attempt to start a transaction
#Transactional(propagation = Propagation.REQUIRED)
public void saveData(DbJndi, EntityA){
//this return false that no transaction started
TransactionSynchronizationManager.isActualTransactionActive();
//create an EntityManager based on the input DbJndi to dynamically
//determine which DB to save the data
EntityManager em = createEm(DbJndi);
//save the data
em.persist(EntityA);
}
}
//restful service
#RestController
class RestController{
#Autowired
DynamicService service;
#RequestMapping( value = "/saveRecord", method = RequestMethod.POST)
public #ResponseBody String saveRecord(){
//save data
service.saveData(...)
}
}
//startup application
#SpringBootApplication
class TestApp {
public static void main(String[] args) {
SpringApplication.run(TestApp.class, args);
}
}
persistence.xml
-------------------------------------------
<persistence-unit name="PU1" transaction-type="JTA">
<properties>
<!-- comment for spring to handle transaction??? -->
<!--property name="eclipselink.target-server" value="WebLogic_10"/ -->
</properties>
</persistence-unit>
-------------------------------------------
application.properties (just 3 lines of config)
-------------------------------------------
spring.jta.enabled=true
spring.jta.log-dir=spring-test # Transaction logs directory.
spring.jta.transaction-manager-id=spring-test
-------------------------------------------
My usage pattern does not follow most typical use cases (e.g. with known number of DBs - Spring + JPA + multiple persistence units: Injecting EntityManager).
Can anybody give me advice on how to solve this issue?
Is there anybody who has ever hit this situation that the DBs are not known in design time?
Thank you.
I finally got it work with:
Enable tomcat JNDI and create the datasource JNDI to each DS programmatically
Add transaction stuff
com.atomikos:transactions-eclipselink:3.9.3 (my project uses eclipselink instead of hibernate)
org.springframework.boot:spring-boot-starter-jta-atomikos
org.springframework:spring-tx
You have pretty much answered the question yourself: "When deployed in a EJB container (e.g. WebLogic), with proper TransactionAttribute (e.g. TransactionAttributeType.REQUIRED), the container will take care of the transaction start/end/rollback".
WebLogic is compliant with the Java Enterprise Edition specification which is probably why it worked before, but now you are using Tomcat (in embedded mode) which are NOT.
So you simply cannot do what you are trying to do.
This statement in your persistence.xml file:
<persistence-unit name="PU1" transaction-type="JTA">
requires an Enterprise Server (WebLogic, Glassfish, JBoss etc.)
With Tomcat you can only do this:
<persistence-unit name="PU1" transaction-type="RESOURCE_LOCAL">
And you need to handle transactions by your self:
myEntityManager.getTransaction.begin();
... //Do your transaction stuff
myEntityManager.getTransaction().commit();
I m having a problem with ServiceMix and JPA.
I m new on servicemix and on the project I work for.
A bundle already exist to set the database configuration and contains a persistence.xml file with some properties in persistence-unit.
this persistent unit is for a postgresql database and work fine.
Recently someone add a new bundle. This bundle is a migration of an existing application that contains work to clean all table in relation with the treatment to have empty db -> readfile-> insert into db some data-> extract data into file for another application.
Now in OSGI bundle, we decide to create an H2 database with spring-context each time the process is launch. We work in memory and we don t have to clean all table with this solution.
So we have done a blueprint.xml that launch a bean, and the bean create a appContext = new OsgiBundleXmlApplicationContext(...)
And when treatment is done we do appContext.close() and all spring context is destroy. (this treatment is run only once a day so no problem with time loading)
To do so we have an applicationContext.xml that contain
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
...
<bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
....
....
All work fine, Spring Context is loaded with H2 in memory databse, and at the end of the treatment, h2 database not exist anymore.
Now the problem is when a query is launch on postgresql database, i have problem with insertion because entitymanager try to save entity with 0 id!
O id is meaning null because we don't allow-zero-id in persistence.xml for postgressql database, but in persistence.xml for H2 databse we set allow-zero-id to true and if the H2 treatment is launch only one time, the other entitymanager(postrgesql) don't work anymore and try to insert always 0 id in database instead of call sequence because of the allow-zero-id.
I don't now why the property for persistent unit defined in H2 databse ovveride property of persistence-unit of postgresql.
If someone can help? does new OsgiBundleXmlApplicationContext(..) try to find an osgi service for entitymaneger and get an existing one instead of create à new one?
I have a vanilla maven WAR project, using the Java EE web profile, that executes its unit/integration tests using OpenEJB. During the OpenEJB start-up, instead of using the data source defined in jndi.properties, OpenEJB creates its own:
INFO - Auto-creating a Resource with id 'Default JDBC Database' of type 'DataSource for 'scmaccess-unit'.
INFO - Creating Resource(id=Default JDBC Database)
INFO - Configuring Service(id=Default Unmanaged JDBC Database, type=Resource, provider-id=Default Unmanaged JDBC Database)
INFO - Auto-creating a Resource with id 'Default Unmanaged JDBC Database' of type 'DataSource for 'scmaccess-unit'.
INFO - Creating Resource(id=Default Unmanaged JDBC Database)
INFO - Adjusting PersistenceUnit scmaccess-unit <jta-data-source> to Resource ID 'Default JDBC Database' from 'jdbc/scmaccess'
INFO - Adjusting PersistenceUnit scmaccess-unit <non-jta-data-source> to Resource ID 'Default Unmanaged JDBC Database' from 'null'
And then, further below, when it's time to create the table - as per the create-drop strategy defined on the app's persistence.xml file - I see several errors like this:
(...) Internal Exception: java.sql.SQLSyntaxErrorException: type not found or user lacks privilege: NUMBER
Error Code: -5509
The jndi.properties file:
##
# Context factory to use during tests
##
java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory
##
# The DataSource to use for testing
##
scmDatabase=new://Resource?type=DataSource
scmDatabase.JdbcDriver=org.hsqldb.jdbcDriver
scmDatabase.JdbcUrl=jdbc:hsqldb:mem:scmaccess
##
# Override persistence unit properties
##
scmaccess-unit.eclipselink.jdbc.batch-writing=JDBC
scmaccess-unit.eclipselink.target-database=Auto
scmaccess-unit.eclipselink.ddl-generation=drop-and-create-tables
scmaccess-unit.eclipselink.ddl-generation.output-mode=database
And, the test case:
public class PersistenceTest extends TestCase {
#EJB
private GroupManager ejb;
#Resource
private UserTransaction transaction;
#PersistenceContext
private EntityManager emanager;
public void setUp() throws Exception {
EJBContainer.createEJBContainer().getContext().bind("inject", this);
}
public void test() throws Exception {
transaction.begin();
try {
Group g = new Group("Saas Automation");
emanager.persist(g);
} finally {
transaction.commit();
}
}
}
Looks like eclipselink is trying to create a column with the type NUMBER and that type does not exist in HSQL. Did you specify that type in your mappings? If yes then fix that.
Otherwise it might help to add
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.create-ddl-jdbc-file-name" value="createDDL_ddlGeneration.jdbc"/>
<property name="eclipselink.drop-ddl-jdbc-file-name" value="dropDDL_ddlGeneration.jdbc"/>
<property name="eclipselink.ddl-generation.output-mode" value="both"/>
to your persistence.xml so you can see what create table statements are exactly generated. If eclipselink is using NUMBER on it's own for certain columns you can tell it to use something else by using the following annotations on the corresponding fields.
#Column(columnDefinition="NUMERIC")
I need to detach some entity objects from the database to make them unmanaged. I use EclipseLink persistence provider, which method EntityManager.detach() is exactly one I need. The problem is that JBoss throws at runtime following exception (when execution passes to detach()):
javax.ejb.EJBTransactionRolledbackException: Unexpected Error
java.lang.NoSuchMethodError: javax.persistence.EntityManager.detach(Ljava/lang/Object;)V
Other methods like persist, merge, find work fine. I tried Hibernate and know that its Session provides a special method evict(), which detaches entity, but EclipseLink has no such method.
Example of using detach():
#PersistenceContext(unitName="Course7-ejbPU")
protected EntityManager manager;
(...)
Query query;
List<Message> resultList;
query = manager.createNamedQuery("Message.getUserInputMessageList");
query.setParameter("login", login);
query.setMaxResults(5);
resultList = query.getResultList();
for (Message message : resultList)
if (message.getContent().length() > 50)
{
manager.detach(message);
message.setContent(message.getContent().substring(0, 50) + "...");
}
Persistence.xml:
<?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="Course7-ejbPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>java:/Course7ds</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-server" value="JBoss"/>
</properties>
</persistence-unit>
</persistence>
Library with provider data is included into ear archive.
EclipseLink version is 2.2.0 (tested with 2.3.2 - no difference), JBoss server version 5.1.0. Any suggestions will be appreciated.
This exception shows that you're not using JPA2, but JPA1. You should probably use a more recent version of JBoss, that ships with JPA2.
You compiled your code with JPA 2.0 classes, but you run it with JPA 1.0. This is why the JVM doesn't find the detach method.
In reaction to your comment: no, the detach method is not useless for JPA 1.0 user: it's just it has not been created yet. You can however erase all the L1 cache by calling clean() on the entitymanager, which will detach all your managed entities...
You can still be able to detach an entity by using persistence provider specific code.
It is not because the entity manager does not provide a function yet, that the jpa providers hasn't implemented it yet.
If you can couple a little bit your code to your jpa provider:
You can call the em.getDelegate() method that will return you an EclipseLink entity manager implementation (check in debug the returned value and cast it) which may perhaps give you the possibility to detach your entity.
The method may not be named detach() -> for Hibernate it's evict().
I have a perfectly working application client deployed to a GlassFish v2 server inside an ear with some EJBs, Entities, etc. I'm using eclipselink.
Currently I have in my persistence.xml:
<persistence-unit name="mysource">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/mysource</jta-data-source>
<class>entities.one</class>
<class>entities.two</class>
...
<properties>
<property name="eclipselink.target-server" value="SunAS9"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
And this works fine when I inject the EntityManager into the EJB:
#PersistenceContext(unitName="mysource")
private EntityManager em;
Now I have a requirement to dynamically switch persistence units/databases.
I figure I can get an EntityManager programatically:
em = Persistence.createEntityManagerFactory("mysource").createEntityManager();
but I get the following error:
Unable to acquire a connection from driver [null], user [null] and URL [null]
Even "overriding" javax.persistence.jtaDataSource" to "jdbc/mysource" in a Map and calling createEntityManagerFactory("mysource", map) doesn't make a difference.
What am I missing?
You are trying to circumvent the container with creating an entity manager programmatically and this means you'll most probably create a non-JTA data source (as it's outside the container, the transaction type should be RESOURCE_LOCAL), thus your original config is useless.
Try injecting an entity manager with a different unitName property or create a RESOURCE_LOCAL transaction type persistence unit.