JBoss 7 & EJB3 | Where should I define datasource - java

I'm new to Jboss and I don't understand where should I define the database connection data like url, username, password etc..
Here is my multimodule project:
app-root
app-api
- src
- pom.xml
app-ear
- src
- pom.xml
app-ejb
- src
- pom.xml
pom.xml
My persinstence.xml located unter app-root/app-ejb/src/main/config/default/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="ejb3_jpa_myapp_pu" transaction-type="JTA">
<description>Jboss Test application</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jdbc/MyApp</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
And finaly my simple Service:
#Stateless
#Remote(IService.class)
public class ServiceImpl implements IService{
#PersistenceContext(unitName = "ejb3_jpa_myapp_pu")
private EntityManager em;
#Override
public void doSomeJob() {
// [...]
}
}
I know I have to define the database connection properties but where can I do that?

You need to define the data source in the standalone XML file that your JBoss instance is using. JBoss does not ship with database drivers so there are two steps:
1) Create a JBoss module for the database drivers (eg MySQL, Oracle, Postgres etc)
2) Create the datasource definition
Step 1) needs only to be done once, ie many MySQL datasources can use the same MySQL JBoss module.
Step 2) An example datasource configuration for MySQL would be:
<datasources>
<datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS">
<connection-url>jdbc:mysql://localhost:3306/EJB3</connection-url>
<driver>com.mysql</driver>
<transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
<pool>
<min-pool-size>10</min-pool-size>
<max-pool-size>100</max-pool-size>
<prefill>true</prefill>
</pool>
<security>
<user-name>test</user-name>
<password>test</password>
</security>
<statement>
<prepared-statement-cache-size>32</prepared-statement-cache-size>
<share-prepared-statements/>
</statement>
</datasource>
<drivers>
<driver name="com.mysql" module="com.mysql">
<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
</driver>
</drivers>
</datasources>
The above can be automated using the JBoss CLI. Also creating the JBoss modules can also be automated for example using the smartics-jboss-modules-maven-plugin see Generate an xml file with all dependencies with maven for more info.

Related

Hibernate EntityManager not managed by wildfly

I'm trying to add hibernate to old project that is currently using plain SQLs + SeesionContext/DataSource classes. My problem is that I can't force Wildfly (version 21) to manage EntityManager. Persistence.createEntityManagerFactory("customJpa").createEntityManager(); is working correctly, persistence.xml file is read correctly.
I've tried to inject #PersistenceUnit for EntityManagerFactory, add hibernate annotations repo etc. but without any success. I'm basically stuck after trying every possible solution I've found in documentation or here.
I'm probably doing some silly mistake, but I can't figure that out.
persistence.xml file is located under src\main\resources\META-INF\persistence.xml, in WAR - deployments\project.war\WEB-INF\classes\META-INF\persistence.xml.
build.gradle:
implementation([
...
'org.hibernate:hibernate-core:5.6.3.Final',
'com.oracle.ojdbc:ojdbc8:19.3.0.0'
])
Persistence.xml file looks like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="customJpa" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:/jdbc/customDS</jta-data-source>
<class>com.entities.Entity</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.implicit_naming_strategy" value="org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl"/>
<property name="hibernate.search.default.worker.backend" value="jms"/>
<property name="hibernate.search.default.worker.jms.connection_factory" value="java:/ConnectionFactory"/>
<property name="hibernate.search.default.directory_provider" value="filesystem"/>
<!-- Uncomment only for debugging -->
<!--<property name="hibernate.show_sql" value="true"/>-->
<!--<property name="hibernate.format_sql" value="true"/>-->
</properties>
</persistence-unit>
</persistence>
DB settings file:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<xa-datasource jndi-name="java:/jdbc/customDS" pool-name="pollXADS">
<xa-datasource-class>...</xa-datasource-class>
<xa-datasource-property name="URL">...</xa-datasource-property>
<driver>ojdbc7.jar</driver>
<security>
<user-name>...</user-name>
<password>...</password>
</security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker"/>
<stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker"/>
<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter"/>
</validation>
<xa-pool>
<min-pool-size>0</min-pool-size>
<max-pool-size>30</max-pool-size>
<is-same-rm-override>false</is-same-rm-override>
</xa-pool>
<timeout>
<blocking-timeout-millis>10000</blocking-timeout-millis>
<idle-timeout-minutes>10</idle-timeout-minutes>
</timeout>
</xa-datasource>
</datasources>
Java base repo class:
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public abstract class BaseRepositoryImpl<Entity, Id> implements BaseRepository<Entity, Id>
{
private final Class<Entity> clazz;
#PersistenceContext(unitName = "customJpa")
private final EntityManager em;
protected BaseRepositoryDAO(Class<Entity> clazz)
{
this.clazz = clazz;
this.em = getEntityManager();
}
...
//Workaroud - creating entityManager using Persistence class is working
protected EntityManager getEntityManager()
{
if (em != null)
{
return em;
}
return Persistence.createEntityManagerFactory("customJpa").createEntityManager();
}

No Persistence provider for EntityManager named- when try to deploy from weblogic console

I'm struggling for a few days about this error.
When I try to deploy from ide(IntelliJ-eclipse), it works correct.
But when I try to deploy from WebLogic console, I got these errors;
Error Unable to access the selected application.
Error Unable to invoke Annotation processoror.
Error Unable to invoke Annotation processoror.
For more information, I checked logs and errors from stack trace.
It looks like the main error is: javax.persistence.PersistenceException: No Persistence provider for EntityManager named.
In debug, throwing from this code; Persistence.createEntityManagerFactory("persistanceUnitName");
Persistence classes are coming from javaee-web-abi-7.0.jar.
Everything looks fine in 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="persistanceUnitName"
transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>dataSource</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="Oracle" />
<property name="eclipselink.logging.parameters" value="true" />
<property name="eclipselink.logging.logger" value="DefaultLogger" />
<property name="eclipselink.logging.level" value="WARNING" />
<property name="eclipselink.refresh" value="true" />
<property name="eclipselink.query-results-cache" value="false" />
<!-- <property name="eclipselink.ddl-generation" value="create-or-extend-tables" />-->
</properties>
</persistence-unit>
</persistence>
persistance.xml located in /WEB-INF/classes/META-INF
We got a case like that: we have a test and prep environment. In test, it works, in prep doesn't work, in local doesn't work (from WebLogic console). Unfortunately, I can't see test server configs. But I expect the same options with prep. Anyway forget other environments, firstly I need to deploy successful from local.
Could you pls help me, I really don't know what I miss. Read every topic, tried everything
It looks like a classpath issue. Check your weblogic classpath.
If you are using eclipselink library must be loaded first when you are deploying.
Check this.
Add eclipselink into your project with scope provided:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
<scope>provided<scope>
</dependency>
add same dependency into your weblogic classpath:
$WEBLOGIC_HOME/user_projects/domains/base_domain/lib
Then, add below to your weblogic.xml to use eclipselink library.
<wls:container-descriptor>
<wls:prefer-application-packages>
<wls:package-name>org.eclipse.persistence.*</wls:package-name>
</wls:prefer-application-packages>
</wls:container-descriptor>

Openshift doesn't deploy persistence.xml?

Hello there internet community,
So I went into JAVA and started test things localy on my WildFly 8. Everything is OK with maven web projects, looks and works good. Now I decided to go to openshift as the first choice of free cloud for JAVA. I managed to do all needed to get my eclipse and enviorment to work/upload/update server. Then I decided to add MySQL with JPA/Hibernate and localy everything is OK. BUT, when I upload to openshift I get the following error:
2015-05-30 06:18:13,289 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC000001: Failed to start service jboss.deployment.unit."ROOT.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."ROOT.war".WeldStartService: Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1904) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_45]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_45]
Caused by: java.lang.IllegalArgumentException: JBAS016069: Error injecting persistence unit into CDI managed bean. Can't find a persistence unit named in deployment ROOT.war
at org.jboss.as.weld.services.bootstrap.WeldJpaInjectionServices.getScopedPUName(WeldJpaInjectionServices.java:110)
at org.jboss.as.weld.services.bootstrap.WeldJpaInjectionServices.registerPersistenceContextInjectionPoint(WeldJpaInjectionServices.java:73)
at org.jboss.weld.injection.ResourceInjectionFactory$PersistenceContextResourceInjectionProcessor.getResourceReferenceFactory(ResourceInjectionFactory.java:313)
at org.jboss.weld.injection.ResourceInjectionFactory$PersistenceContextResourceInjectionProcessor.getResourceReferenceFactory(ResourceInjectionFactory.java:301)
at org.jboss.weld.injection.ResourceInjectionFactory$ResourceInjectionProcessor.createFieldResourceInjection(ResourceInjectionFactory.java:207)
at org.jboss.weld.injection.ResourceInjectionFactory$ResourceInjectionProcessor.createResourceInjections(ResourceInjectionFactory.java:182)
at org.jboss.weld.injection.ResourceInjectionFactory.discoverType(ResourceInjectionFactory.java:405)
at org.jboss.weld.injection.ResourceInjectionFactory.getResourceInjections(ResourceInjectionFactory.java:92)
at org.jboss.weld.injection.producer.ResourceInjector.(ResourceInjector.java:59)
at org.jboss.weld.injection.producer.ResourceInjector.of(ResourceInjector.java:49)
at org.jboss.weld.injection.producer.BeanInjectionTarget.(BeanInjectionTarget.java:62)
at org.jboss.weld.injection.producer.BeanInjectionTarget.createDefault(BeanInjectionTarget.java:46)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.chooseInjectionTarget(InjectionTargetFactoryImpl.java:128)
at org.jboss.weld.manager.InjectionTargetFactoryImpl.createInjectionTarget(InjectionTargetFactoryImpl.java:87)
at org.jboss.weld.bean.ManagedBean.(ManagedBean.java:91)
at org.jboss.weld.bean.ManagedBean.of(ManagedBean.java:71)
at org.jboss.weld.bootstrap.AbstractBeanDeployer.createManagedBean(AbstractBeanDeployer.java:264)
at org.jboss.weld.bootstrap.BeanDeployer.createClassBean(BeanDeployer.java:228)
at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$2.doWork(ConcurrentBeanDeployer.java:78)
at org.jboss.weld.bootstrap.ConcurrentBeanDeployer$2.doWork(ConcurrentBeanDeployer.java:75)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:60)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:53)
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [rt.jar:1.8.0_45]
... 3 more
as you can see the error comes from
JBAS016069: Error injecting persistence unit into CDI managed bean. Can't find a persistence unit named in deployment ROOT.war
here is my PersistenceContext injection point:
<pre><code>
#SessionScoped
public class IndexWebBean implements Serializable {
private static final long serialVersionUID = 1L;
#PersistenceContext
EntityManager em;
#Inject
SettingsBean settingsBean;
private boolean isUserAdmin = true;
private String selectedTheme = "aristo";
private String aboutMessage;
private NotificationController notificationController;
public IndexWebBean() {}
#PostConstruct
public void Init() {}
}
</code></pre>
here is persistence.xml:
<pre><code>
<persistence-unit name="ROOT">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/MySQLDS</jta-data-source>
<class>ROOT.ROOT.entity.User</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="UTF-8" />
</properties>
</persistence-unit>
</code></pre>
standalone.xml:
<pre><code>
<datasources>
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>
<datasource jta="true" jndi-name="java:jboss/datasources/MySQLDS" pool-name="MySQL" enabled="true" use-ccm="true">
<connection-url>jdbc:mysql://localhost:3306/crafty</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver>com.mysql</driver>
<security>
<user-name>XX</user-name>
<password>XX</password>
</security>
<validation>
<validate-on-match>false</validate-on-match>
<background-validation>false</background-validation>
</validation>
<timeout>
<set-tx-query-timeout>false</set-tx-query-timeout>
<blocking-timeout-millis>0</blocking-timeout-millis>
<idle-timeout-minutes>0</idle-timeout-minutes>
<query-timeout>0</query-timeout>
<use-try-lock>0</use-try-lock>
<allocation-retry>0</allocation-retry>
<allocation-retry-wait-millis>0</allocation-retry-wait-millis>
</timeout>
<statement>
<share-prepared-statements>false</share-prepared-statements>
</statement>
</datasource>
<drivers>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
<driver name="com.mysql" module="com.mysql"/>
</drivers>
</datasources>
</code></pre>
(alot of text has been outputed, so quick reminder: localy eveyrthing works like a charm)
So I went with "rhc ssh -a appname" and checked that in wildfly/standalone/deployments/ROOT.war IS compiled in standalone WAR file, while in local system the whole project is folder based - it's not compiled to WAR. That's NOT especialy a bad thing, but the point is that when I unziped the WAR, I checked if folder structure is the same as local folder structure. It seems that it's NOT. There is not META-INF in ROOT.war/WEB-INF/classes where persistence.xml actually stands ... that was a strange one! What I did is to add #PersistenceContext(unitName="ROOT") to em injection point, manualy create that folder (META-INF), manualy upload my persistence.xml from local computer, and rename ROOT.war.failed to ROOT.war.dodeply to re-deploy, and it worked. But then I made some changes to the code localy, again it worked like a charm, published to openshift thru eclipse and still openshift complied my ROOT.war to webarch and META-INF and standalone.xml are nowhere to be found which yet leaded to the same error. So my question is: what am I doing wrong if everything works great localy, and doesn't when is uploaded to openshift? Thanks in advance for your time.
PS.: English is not my native sorry for any errors. I hope everything is readable and understandable. Any more additional info I will provide on demand.

What is wrong with this persistence unit configuration?

I am trying to set up a persistence unit in JEE 6 on JBoss AS 6.
The injected EntityManager is always null. I've fiddled around with the configuration quite a bit but can't get anything to work. I've tried JTA/LOCAL_RESOURCE, I've tried using a unit name in my code the same as in my persistence.xml, but also with the war name prepended, as the log suggests the JNDI name might be that.
I have a mysql-ds.xml file as follows:
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>myconnection</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/cog1</connection-url>
<driver-class>org.gjt.mm.mysql.Driver</driver-class>
<user-name>bw</user-name>
<password></password>
<min-pool-size>2</min-pool-size>
<max-pool-size>20</max-pool-size>
<idle-timeout-minutes>5</idle-timeout-minutes>
<exception-sorter-class-name>com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter</exception-sorter-class-name>
<valid-connection-checker-class-name>com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker</valid-connection-checker-class-name>
</local-tx-datasource>
</datasources>
I have a persistence.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<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.0">
<persistence-unit name="myunit" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:/myconnection</jta-data-source>
<non-jta-data-source>java:/myconnection</non-jta-data-source>
<class>com.cognitura.simulation.dao.model.History</class>
<properties>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO" />
</properties>
</persistence-unit>
</persistence>
And I have a bean with the following code in it:
#Stateful
#LocalBean
public class HistoryEJB {
#PersistenceContext(unitName = "myunit")
private EntityManager em;
#EJB
private RealityElement el;
I can see that the RealityElement el is getting injected fine, so I think it's definitely being container-managed?
Grateful for any ideas!
EDIT: The logs seem to be fine for setting up the 'myunit' unit. There is a warning, but I read that it's not important?
01:28:06,276 INFO [org.jboss.jpa.deployment.PersistenceUnitDeployment] Starting persistence unit persistence.unit:unitN
ame=cog1.war#myunit
01:28:06,278 INFO [org.hibernate.ejb.Ejb3Configuration] Processing PersistenceUnitInfo [
name: myunit
...]
01:28:06,305 WARN [org.hibernate.ejb.Ejb3Configuration] Persistence provider caller does not implement the EJB3 spec co
rrectly.PersistenceUnitInfo.getNewTempClassLoader() is null.
Seems happy here:
01:28:06,965 INFO [org.hibernate.impl.SessionFactoryObjectFactory] Bound factory to JNDI name: persistence.unit:unitNam
e=cog1.war#myunit
Could it be the jndi name? Try making the following changes in datasource and persistence files
<jndi-name>java:jboss/datasources/employeedb</jndi-name>
<jta-data-source>java:jboss/datasources/employeedb</jta-data-source>

JBoss AS 7 Error while deplouing EJBs

I am working through this deployment one step at a time. Did get some answers from people that have helped but I am now stuck on this error:
JBAS014775: New missing/unsatisfied dependencies:
service jboss.naming.context.java.jboss.datasources.DoDSRDS (missing) dependents: [service jboss.persistenceunit."dodsr.ear/dodsr.jar#DoDSRMGR"]
My persistence.xml file is this:
<?xml version="1.0" encoding="windows-1252" ?>
<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_1_0.xsd"
version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="DoDSRMGR">
<jta-data-source>java:jboss/datasources/DoDSRDS</jta-data-source>
<class>mil.army.amedd.dodsr.model.ManifestsPass1</class>
<class>mil.army.amedd.dodsr.model.ManifestsPass2</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="javax.persistence.jtaDataSource" value="java:/DoDSRDS"/>
</properties>
</persistence-unit>
And the datasource in standalone.xml is this:
<datasource jndi-name="java:jboss/datasources/DoDSRDS" pool-name=" DoDSRDS " enabled="true" use-java-context="true">
<connection-url>jdbc:oracle:thin:#160.151.120.38:2115:apdb</connection-url>
<driver>oracle</driver>
<pool>
<prefill>true</prefill>
<use-strict-min>false</use-strict-min>
</pool>
<security>
<user-name>username</user-name>
<password>password</password>
</security>
How do I get this thing to deploy??
There might be 2 potential problems:
The name of the datasource in standalone.xml might be wrong or missing.
You might need to change
<jta-data-source>java:jboss/datasources/DoDSRDS</jta-data-source>
in persistence.xml to
<jta-data-source>java:/DoDSRDS</jta-data-source>.
I'd your main problem is number 2 but number 1 might still be true (you didn't provide the name definition in your post).
Update:
If you don't need to use the name jboss/datasources/DoDSRDS I'd suggest just using DoDSRS, i.e. jndi-name="java:/DoDSRDS" and <jta-data-source>java:/DoDSRDS</jta-data-source>.
Update 2:
A third problem might be the spaces in the pool-name. I'm not sure they're allowed here but at least it might cause problems if you reference the pool by name and don't have the exact same number of spaces, so I'd remove those in any case.

Categories

Resources