7/27/2006

HelloWorld with JPA, TopLink and MySql

This is a simple example of standalone java application using Java Persistence API (JPA), TopLink persistence engine, and MySql. It consists of an entity class, a main class, and a persistence.xml file. No need to create tables, as they are created and dropped automatically.

META-INF/persistence.xml must be at the root of the persistence unit. In my example project, it's C:\ws\nb\scrap\build\classes\META-INF\persistence.xml.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">

<!-- comment out to use the default provider
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
-->

<class>com.foo.Greeting</class>
<properties>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.password" value=""/>
<property name="toplink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
Entity class:
package com.foo;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Greeting implements Serializable {
@Id @GeneratedValue private int id;
@Basic private String message;
@Basic private String language;

public Greeting() {}
public Greeting(String message, String language) {
this.message = message;
this.language = language;
}

public String toString() {
return "Greeting id=" + id + ", message=" + message + ", language=" + language;
}
}
Main class:
package com.foo;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class HelloWorld {
private EntityManagerFactory emf;
private EntityManager em;
private String PERSISTENCE_UNIT_NAME = "hello-world";

public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
hello.initEntityManager();
hello.create();
hello.read();
hello.closeEntityManager();
}

private void initEntityManager() {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
}

private void closeEntityManager() {
em.close();
emf.close();
}

private void create() {
em.getTransaction().begin();
Greeting g_en = new Greeting("hello world", "en");
Greeting g_es = new Greeting("hola, mundo", "es");
Greeting[] greetings = new Greeting[]{g_en, g_es};
for(Greeting g : greetings) {
em.persist(g);
}
em.getTransaction().commit();
}

private void read() {
Greeting g = (Greeting) em.createQuery(
"select g from Greeting g where g.language = :language")
.setParameter("language", "en").getSingleResult();
System.out.println("Query returned: " + g);
}
}
To compile the project,
C:\ws\nb\scrap\src\com\foo>
javac -d C:\ws\nb\scrap\build\classes
-classpath C:\Sun\AppServer\lib\toplink-essentials-agent.jar
Greeting.java HelloWorld.java
To run it, start MySql on localhost, and run
C:\ws\nb\scrap\build\classes>
java -javaagent:C:\Sun\AppServer\lib\toplink-essentials-agent.jar
-cp .;C:\tools\mysql-java\mysql-connector-java-3.1.13-bin.jar
com.foo.HelloWorld

[TopLink Info]: 2006.07.27 01:34:26.484--ServerSession(20003078)--TopLink, version: Oracle TopLink Essentials - 2006.4 (Build 060412)
[TopLink Info]: 2006.07.27 01:34:27.686--ServerSession(20003078)--file:/C:/ws/nb/scrap/build/classes-hello-world login successful
[TopLink Warning]: 2006.07.27 01:34:27.926--ServerSession(20003078)--Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Table 'sequence' already existsError Code: 1050
Call:CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(38), PRIMARY KEY (SEQ_NAME))
Query:DataModifyQuery()
Query returned: Greeting id=1, message=hello world, language=en
[TopLink Info]: 2006.07.27 01:34:28.447--ServerSession(20003078)--file:/C:/ws/nb/scrap/build/classes-hello-world logout successful

69 comments:

Klaus Meffert said...

The size of your example may be quite huge for a helloworld demo. But it seems reasonable OK, because there is no need for creating DB tables, as you wrote.

Is there a possibility of generating part of the stuff with a tool? It frustrates me to be forced to write as much as you indicated to produce a very simple example. I mean, we are living in 21st century. This is no criticism of your entry, but of the status quo of practicability of java tech, which should be much better IMHO.

howto said...

NetBeans 5.5 beta 2 supports JPA and TopLink, and can automate many steps, including generating persistence.xml with a GUI tool, JPA-specific code assist, generate Entity class from existing schemas.

For large apps, I would definitely use some IDE. But for small samples like this, it's not that hard to manage in command line. Plus I want to show how to write Java Persistence apps in general, not how to write them in NetBeans. That's the reason I didn't use NetBeans for this one.

You can also download the Hibernate entity manager module for NetBeans 5.5 beta 2.

http://www.buckadero.se/tmp/org-netbeans-modules-j2ee-hibernatelib.nbm
http://blogs.sun.com/roller/page/pblaha?entry=hibernate_entitymanager_library_for_netbeans

Hibernate Entity Manager is still under development as the time of writing.

Antonio Goncalves said...

I've used your example with Hibernate EntityManager : http://www.jroller.com/page/agoncal?entry=helloworld_with_jpa_hibernate_and

Carl said...

I'd been having a lot of trouble getting started with JPA. Your example was a great help and got me over the hump. Thank you very much!

Abubakar said...

The tutorial was simple and straight to the point.

Thanks alot

sanj said...

Hey,

Thanks for a great how-to. When I initially ran the example I came across this error:

10:20:36.963--UnitOfWork(534353)--java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number

Which I later narrowed down to the mysql driver I was using (mysql-connector-java-3.0.9-stable-bin.jar)
. I got around this by simply using a newer mysql driver (
mysql-connector-java-3.1.14-bin.jar).

Anonymous said...

How do you use javaagent:toplink-essentials.agent.jar in a desktop app without putting the full path in to the VM option ?

For example:
-javaagent:"C:/app/dist/lib/toplink-essentials-agent.jar"

works, but on another computer this path will be different. Can you put a relative path in their such as:
-javaagent:"lib/toplink-essentials-agent.jar"

javahowto said...

Yes, you can also use relative path (relative to where java command is executed). For example,

/home/Hello/build/classes > java -javaagent:../../agent.jar javahowto.Hello

jFreak said...

in persistence.xml
use org.gjt.mm.mysql.Driver as driver

Krishna said...

JPA NetBeans

Anonymous said...

Hi, thanks for such a nice example.
But, i have faced few issues
I am using Eclispe and created jpa project changed the persistance.xml

when HelloWorld is executed i get following error
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named hello-world: The following providers:
oracle.toplink.essentials.PersistenceProvider
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.

at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:154)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
at com.foo.HelloWorld.initEntityManager(HelloWorld.java:21)
at com.foo.HelloWorld.main(HelloWorld.java:14)

could you please check

javahowto said...

WRT to the "no persistence provider" error, I suggest check:

1. toplink-essentials.jar is in your RUNTIME classpath. The provider name is defined by this file inside the jar:

META-INF/services/javax.persistence.spi.PersistenceProvider

2. try running the app from command line to eliminate any Eclipse project configuration error.

3. If you're using EclipseLink (the latest incarnation of TopLink), the provider name is different:

org.eclipse.persistence.jpa.PersistenceProvider

See my post (http://javahowto.blogspot.com/2008/10/helloworld-with-eclipselink-and-mysql.html)

4 For any persistence provider, you can always get its provider name by viewing its
META-INF/services/javax.persistence.spi.PersistenceProvider

Manoj said...

Hey this code very helpful for me
thanx......

Anonymous said...

It is a great example
thank you~

Vatsala said...

I was facing a problem somewhat similar to what you have mentioned here. Having followed your tips, I was able to fix it and then now I have a new error : "User must provide jdbc connection"
I have supplied the correct database name, database URL, the username and password in the persistence.xml and there are no compile time errors. Are you aware of scenarios which result in "User must provide jdbc connection"??

Anonymous said...

Very useful post, thanks.

Christian Bajada said...

Thanks!

Anonymous said...

Excellent work. Very useful for new guys like me. Thanks.

JAvin @ HashTable vs HashMap in Java said...

Good example , would have been better it little shorter.

Javin
How to setup remote debugging in Eclipse

j2EENovice said...

Hello sir i tried to run your example and i am facing tht following issue

log4j:WARN No appenders could be found for logger (org.hibernate.type.BasicTypeRegistry).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named hello-world
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.foo.HelloWorld.initEntityManager(HelloWorld.java:18)
at com.foo.HelloWorld.main(HelloWorld.java:12)

Do you know where can this be from?

javahowto said...

It probably means the provider designated in persistence.xml is not found. You can delete the line in persistence.xml and let the persistence engine to discover the default provider.

oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider (and its shorter-name version oracle.toplink.essentials.PersistenceProvider) is the legacy provider name used in GlassFish v2. In GlassFish 3, the default provider is org.eclipse.persistence.jpa.PersistenceProvider

j2EENovice said...

Thank you for your quick reply. I deleted the line in persistence.xml and my output now display :
log4j:WARN No appenders could be found for logger (org.hibernate.type.BasicTypeRegistry).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: hello-world] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:911)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.foo.HelloWorld.initEntityManager(HelloWorld.java:18)
at com.foo.HelloWorld.main(HelloWorld.java:12)
Caused by: org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available
at org.hibernate.dialect.resolver.DialectFactory.buildDialect(DialectFactory.java:106)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:152)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2833)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2829)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:902)
... 5 more
***************
Why am I getting an hibernate error?
I am using jboss as server and eclipse EE as IDE.

my persistence.xml now is :




com.foo.Greeting











Thanks in advance

j2EENovice said...
This comment has been removed by the author.
j2EENovice said...
This comment has been removed by the author.
j2EENovice said...
This comment has been removed by the author.
j2EENovice said...

I don't know what's wrong but i can't display xml data

javahowto said...

If you are using Hibernate, please see another post:

http://javahowto.blogspot.com/2006/07/helloworld-with-jpa-hibernate-and.html

javahowto said...

When posting xml elements, you will probably need to escape < and >

j2EENovice said...

Thanks for the answer i tried the persistance.xml with hibernate and I don't have error message any more. But it does't create Greeting table in my database. So I created it myself but after I lunched mu helloworld program it delete the table in my database when i try to acces it I have Msg 208, Level 16, State 1, Line 1
Invalid object name 'MyDataBase.dbo.Greeting'.

On the otherside I would like too work with the solution which doesn't use hibernate. I didn't specify any where that I want to use hibernate. Is it normal that I got the hibernate error. How can I get rid of using hibernate? I am sorry for my several questions thanks in advance

j2EENovice said...

I understood, It was because of the hello.closeEntityManager() method i put it in comment and it works now :)

javahowto said...

You can use any compliant JPA implementation, including EclipseLink (formerly known as TopLink), and Hibernate. Every modern application server has a default JPA engine so application developers don't need to specify a provider. In GlassFish v2, it's TopLink Essentials, in GlassFish v3 (probably also in WebLogic), it's EclipseLink. In JBoss, it's Hibernate. In most cases, I would recomment using the default JPA provider in your target appserver.

It should be possible to configure the application server to use a different JPA provider.

For standalone java applications like helloworld, it's just a matter of including a different JPA provider jar file in your client classpath.

j2EENovice said...

Do you have a simple example on how to use anotations to manage foreign key for an entity using hibernate?

javahowto said...

Just use the mapping annotations defined by JPA: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany. See Java EE javadoc for more detals:

http://download.oracle.com/javaee/6/api/javax/persistence/OneToMany.html

j2EENovice said...

Thank you for your precious responses, my ejb module is now more complex and I am using both entity ejb and session ejb but when I run my project I have this error:
[org.jboss.kernel.plugins.dependency.AbstractKernelController] Error installing to Start: name=persistence.unit:unitName=EjbModule.jar#Test_project state=Create: java.lang.RuntimeException: Specification violation [EJB3 JPA 6.2.1.2] - You have not defined a non-jta-data-source for a RESOURCE_LOCAL enabled persistence context named: Test_project.

I’ve been trying to find a way out since yesterday but I don’t find any solution. Many forums suggest to add < jta-data-source > java:/DefaultDS < /jta-data-source > to my persistence.xml but it doesn’t change my error message. Do you have any idea about this? I am really sorry for my several questions.

javahowto said...

Since you are using both JPA entities and session beans, your project looks more like a enterprise application, as opposed to the standalone java application. If that's the case, I would recommend use transaction-type="JTA", not transaction-type="RESOURCE_LOCAL".

This will make the jpa provider use a JBoss-managed datasource and JBoss will manage connection pooling and transaction.

It's very rare, though possible, to use RESOURCE_LOCAL in apps deployed to an appserver.

Double check (1) transaction-type="JTA" is used in persistence.xml

(2) Do not use EntityManagerFactory to createEntityManager. Instead inject EntityManager w/ @PersistenceContext into EJB bean class, or look it up.

j2EENovice said...

Thank you very much my ejb module is now deployed. but when i ty to test it from a main class , i have this error

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at com.foo.Main.main(Main.java:17)

Am I obliged to create a web client to test it?

j2EENovice said...

I finally used sevlet to test it it seems to be handy thank you for all your help

j2EENovice said...

I am back again, when I test my web app I can execume methods which are implemented in session ejb without needing entity ejb
example public void sayHello(){
ssystem.out.println("hello");}
but when i try to run methods which use entity ejb I got this errors
javax.ejb.EJBException: java.lang.IllegalStateException: Illegal to call this method from injected, managed EntityManager


I do not use EntityManagerFactory to createEntityManager, I injected EntityManager @PersistenceContext into EJB bean class as you suggested.

javahowto said...

When using container-managed entity manager, do not call em.close(), or em.getTransaction().

The code and configuration is slightly different between application-managed and container-managed entity manager, due to their different runtime environment.

j2EENovice said...

Hi, it seems to work I can run my web module test without any error. But when I go to check in the DB , there is nothing insered. What seems strange to me is that when I run the program for a second time, i have an error:
Caused by: java.sql.SQLException: Violation of unique constraint SYS_PK_76: duplicate value(s) for column(s) $$ in statement....

what would be normal if the first insertion had worked, the problem is that my tables are empty. Do you have any idea about this?

j2EENovice said...
This comment has been removed by the author.
j2EENovice said...

it's really strange my data are well stored in my DB because I have good result when I try a read method on my DB. But in my db table view , it display empty tables.Even if I run select count(*) in my DBMS I have 0, but from a java program I have the right number, as if my java program were storing data in an other database. Am I missing something?

javahowto said...

The table might have been dropped after test client exists. Check your persistence.xml for property hibernate.hbm2ddl.auto" value="create-drop", which tells hibernate to drop tables. This is convenient for repeated test runs.

j2EENovice said...

My hibernate.hbm2ddl.auto value is "validated", I tried all the possible values validate | update | create | create-drop
but I don't see any change.
<property
what surprise me is that i removed the property
name="hibernate.connection.url" value="jdbc:sqlserver://...
to provoke the failure of connection to my DB, and i still have good results in my eclipse output-> My DB is never accessed?

javahowto said...

It could be other db connection (e.g., the default datasource) is used, instead of the intended one. Can you post your complete persistence.xml, with < and > escaped?

j2EENovice said...
This comment has been removed by the author.
j2EENovice said...

my persistence.xml is:
< ?xml version="1.0" encoding="UTF-8"? >
< persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" >
< persistence-unit name="My_Persistence_Unit" transaction-type="JTA" >
< provider > org.hibernate.ejb.HibernatePersistence < /provider >
< jta-data-source > java:/DefaultDS < /jta-data-source >
< class >com.foo.MyClass1< /class >
< class >com.foo.MyClass2< /class >
< class >com.foo.MyClass3< /class >
< properties >
< property name="hibernate.jndi.class" value="org.jnp.interfaces.NamingContextFactory"/ >
< property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" / >
< property name="hibernate.hbm2ddl.auto" value="create"/ >
< property name="hibernate.show_sql" value="false" / >
< property name="hibernate.format_sql" value="false" / >
< property name="jboss.entity.manager.factory.jndi.name" value="java:/agentmanagerEntityManagerFactory" / >
< property name="hibernate.connection.url" value="jdbc:sqlserver://MyServerIP;databaseName=MyDBname;integratedSecurity=true"/ >
< property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/ >

< /properties >
< /persistence-unit >

< /persistence >


When I run my entity class from a main java class I have all updates in my DB but not when I use JSP-Servlet-SessionBean-EntityBean.

The differences between the main java class and the use of JSP-Servlet-SessionBean-EntityBean are:
1. For the main Java program :
private EntityManagerFactory emf;
private EntityManager em;
private String PERSISTENCE_UNIT_NAME = "My_Persistence_Unit";

public void initEntityManager() {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
}
public void create() {
em.getTransaction().begin();
.....
em.persist(...);
em.getTransaction().commit();
}
This works, I can see all my updates in my DB

2. For the project where I use JSP-Servlet-SessionBean-EntityBean :
@PersistenceContext
private EntityManager em;

There is no initEntityManager() as you told me I don't have to use EntityManagerFactory, so my create method is just
public void create() {

em.persist(...);

}

and my Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {
Context ctx = new InitialContext();
Object obj = ctx.lookup("MyJNDIname/Local");
if (obj != null){
MybeanInterfaceLocal realObject = (MybeanInterfaceLocal) obj;
.....
realObject.create();
There is no update in my Database but I can see in my eclipse output:
09:47:10,593 INFO [STDOUT] Count result:3
09:47:10,593 INFO [STDOUT] The list of opened ports on this destination is : [8080, 21, 443, 1723]

My additionnal question is : How is the entityManager initialized in the second case? as I don't use any more EntityManagerFactory and thus no initEntityManager() method?

j2EENovice said...

Count result:3& The list of opened ports on this destination.... displays are managed im methods implemented in my session bean

javahowto said...

As I mentioned earlier, persistence.xml and application code are different depending on the target runtime environment (standalone java application, or Java EE environment).

Your persistence.xml contains elements for both. When running as servlet-ejb-entity, the JTA datasource (java:/defaultDS) will be used. Looks like the default datasource in jboss connecting to the in-memory db hypersonic. So any db updates go to the in-memory db. Any DriverManager-based connections are just ignored.

When running in standalone java application, the JTA datasource is ignored and DriverManager-based connections are used to connect to your mysql db.

That explains the missing db rows when running your app inside server.

j2EENovice said...
This comment has been removed by the author.
j2EENovice said...
This comment has been removed by the author.
j2EENovice said...

I am sorry, there is something I am not getting because my english is not nice I am french. You mean I can't have both 1.(< jta-data-source >java:/DefaultDS< /jta-data-source >)
and 2.(
< property name="jboss.entity.manager.factory.jndi.name" value="java:/agentmanagerEntityManagerFactory"/ >
< property name="hibernate.connection.url" value="jdbc:sqlserver://Myserver;databaseName=MyDatabase;integratedSecurity=true"/ >
< property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/ >


)
in my case as it's servlet-ejb-entity I should only use the first option, right? in any case, Will there be a problem that my data go to the in-memory db? Can I continue building my application without worry?

javahowto said...

The appserver may tolerate having both in persistence.xml, pick one and silently ignore the other. In any event, only one will be used.

As a rule of thumb,

In servlet-ejb-entity case, use JTA transaction type and jta-datasource.

In standalone java applications, use RESOURCE_LOCAL transaction type and driver manager properties.

j2EENovice said...

Thank you very much sir. In the case the default jboss datasource is used, is there any specific file on my computer where the data are stolen after I have done my write operations, stop eclipse and jboss?

j2EENovice said...

...\jbossFolder\server\default\data\hypersonic if it can help someone else

j2EENovice said...
This comment has been removed by the author.
j2EENovice said...

Hello Sir! I continued working with the default jta datasource, but I can't find my data after i close eclipse and jboss. In case we use servlet-ejb-entity, is there any way to use RESOURCE_LOCAL like in helloworld? My main concern is to store my data not in the default jta data source but in a sql server database that I can consult at any

javahowto said...

To store data in mssql instead of the default jboss datasource in your servlet-ejb-entity case, you just need to create a new DataSource in JBoss, and just use that DataSource in persistence.xml. Your persistence.xml should still has transaction-type JTA, and does not need to include all these connection properties.

Also when running in appserver, you do not need to list all entity classes in persistence.xml. It's only needed when running in standalone java applications.

j2EENovice said...

Hello! I put the mssql-ds.xml file under jboss\server\default\deploy location
< datasources >
< local-tx-datasource >
< jndi-name>SampleDS
< connection-url>jdbc:sqlserver://localhost:3306;databaseName=maDatabase;integratedSecurity=true
< driver-class >com.mysql.jdbc.Driver< /driver-class >
< min-pool-size>1>/min-pool-size >
< max-pool-size>20>/max-pool-size >






My persistence.xml now looks like this: < ?xml version="1.0" encoding="UTF-8"? >
< persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" >
< persistence-unit name="Network_topology_manager" transaction-type="JTA" >
< provider>org.hibernate.ejb.HibernatePersistence
java:/SampleDS
< properties >
< property name="hibernate.jndi.class" value="org.jnp.interfaces.NamingContextFactory"/ >
< property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" / >
< property name="hibernate.hbm2ddl.auto" value="create"/ >
< property name="hibernate.show_sql" value="false" / >
< property name="hibernate.format_sql" value="false" / >
< property name="jboss.entity.manager.factory.jndi.name" value="java:/agentmanagerEntityManagerFactory" / >
< /properties >
< /persistence-unit >
< /persistence >
I also deleted hsqldb-ds.xml file under jboss\server\default\deploy.
And when I try to deploy my ejb module I have this error


Failed to create Resource EjbModule.jar - cause: java.lang.Exception:Failed to start deployment [vfs:///D:/Documents/Development/jboss-6.0.0.Final/server/default/deploy/EjbModule.jar] during deployment of 'EjbModule.jar' - cause: java.lang.RuntimeException:org.jboss.deployers.client.spi.IncompleteDeploymentException: Summary of incomplete deployments (SEE PREVIOUS ERRORS FOR DETAILS): DEPLOYMENTS MISSING DEPENDENCIES: Deployment "jboss.j2ee:jar=EjbModule.jar,name=NetworkManager,service=EJB3" is missing the following dependencies: Dependency "" (should be in state "Installed", but is actually in state "** UNRESOLVED Demands 'jboss.ejb:service=EJBTimerService' **") Dependency "" (should be in state "Installed",.....

javahowto said...

I would not delete the default jboss hypersonic datasource file. Looks like DefaultDS is also used for ejb timer service to store timers. When deploying your ejb jar, jboss tried to activate ejb timer service but failed.

It's ok to keep multiple datasources in appserver, as long as you reference the correct one in your persistence.xml

j2EENovice said...

I still have huge number of errors when I try to deploy , The complete output is
Failed to create Resource EjbModule.jar - cause: java.lang.Exception:Failed to start deployment [vfs:///D:/Documents/Development/jboss-6.0.0.Final/server/default/deploy/EjbModule.jar] during deployment of 'EjbModule.jar' - cause: java.lang.RuntimeException:org.jboss.deployers.client.spi.IncompleteDeploymentException: Summary of incomplete deployments (SEE PREVIOUS ERRORS FOR DETAILS): DEPLOYMENTS MISSING DEPENDENCIES: Deployment "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3" is missing the following dependencies: Dependency "" (should be in state "Installed", but is actually in state "** UNRESOLVED Demands 'persistence.unit:unitName=EjbModule.jar#MyUnitName' **") Deployment "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3,type=nointerface-view-jndi-binder" is missing the following dependencies: Dependency "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3" (should be in state "Installed", but is actually in state "PreInstall") Deployment "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3_endpoint" is missing the following dependencies: Dependency "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3" (should be in state "Installed", but is actually in state "PreInstall") Deployment "persistence.unit:unitName=EjbModule.jar#MyUnitName" is missing the following dependencies: Dependency "jboss.jca:name=SampleDS,service=DataSourceBinding" (should be in state "Create", but is actually in state "** NOT FOUND Depends on 'jboss.jca:name=SampleDS,service=DataSourceBinding' **") DEPLOYMENTS IN ERROR: Deployment "jboss.jca:name=SampleDS,service=DataSourceBinding" is in error due to the following reason(s): ** NOT FOUND Depends on 'jboss.jca:name=SampleDS,service=DataSourceBinding' ** Deployment "" is in error due to the following reason(s): ** UNRESOLVED Demands 'persistence.unit:unitName=EjbModule.jar#MyUnitName' ** -> org.jboss.deployers.client.spi.IncompleteDeploymentException:Summary of incomplete deployments (SEE PREVIOUS ERRORS FOR DETAILS): DEPLOYMENTS MISSING DEPENDENCIES: Deployment "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3" is missing the following dependencies: Dependency "" (should be in state "Installed", but is actually in state "** UNRESOLVED Demands 'persistence.unit:unitName=EjbModule.jar#MyUnitName' **") Deployment "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3,type=nointerface-view-jndi-binder" is missing the following dependencies: Dependency "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3" (should be in state "Installed", but is actually in state "PreInstall") Deployment "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3_endpoint" is missing the following dependencies: Dependency "jboss.j2ee:jar=EjbModule.jar,name=MyProject,service=EJB3" (should be in state "Installed", but is actually in state "PreInstall") Deployment
…..
Enter the absolute path to the local file you wish to deploy, specify deployment options, then click Continue.

javahowto said...

reinstall jboss.

j2EENovice said...
This comment has been removed by the author.
j2EENovice said...

My new error is
deployment "jboss.jca:name=mssql-ds,service = DataSourceBinding" is in error due to the following reason():**not found depends jboss.jca:name = mssql-ds,service = DataSourceBinding...
My full mssql-ds.xml is < ?xml version="1.0" encoding="UTF-8"? >
< datasources >
< local-tx-datasource >
< jndi-name >MSSQLDS< /jndi-name >
< connection-url >jdbc:sqlserver://localhost:3306;databaseName=maDatabase;integratedSecurity=true < /connection-url >
< driver-class >com.microsoft.sqlserver.jdbc.SQLServerDriver< /driver-class >
< user-name >< /user-name >
< password >< /password >
< metadata >
< type-mapping>MS SQLSERVER2000< /type-mapping >
< /metadata >
< /local-tx-datasource >

< /datasources >

and the entry I added to my persistence.xml is < jta-data-source >java:/mssql-ds< /jta-data-source >

July 19, 2011 4:40 AM

javahowto said...

The datasource name is different in persistence.xml and ms-sql-ds.xml, so at deployment time the jta-data-source in persistence.xml is not found.

j2EENovice said...

Thank you very much, I am getting an other error "javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Cannot open connection
"
root cause

org.hibernate.exception.GenericJDBCException: Cannot open connection


root cause

org.jboss.util.NestedSQLException: Unable to get managed connection for MSSQLDS; - nested throwable: (javax.resource.ResourceException: Unable to get managed connection for MSSQLDS.

I added my jdbc jar sqljdbc4.jar under ...\jboss-6.0.0.Final\lib but I still have the same error

javahowto said...

If you have copied the above mssql-ds.xml to server/default/deploy directory, then your persistence.xml should use "java:/MSSQLDS" as the jta-data-source.

I usually copy the driver jars to server/default/lib.

j2EENovice said...

It works. Thank you for your several helps and valuable guidance.

Dev said...

Thanks for the examples, the issues that I am facing with my code is that when I enter data in the table using JPA, only the last entry remains and all the other get flushed out with the entry of the new one

My Entity class is as
import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

@Entity
public class Book implements Serializable{
@SequenceGenerator(name="bookid", sequenceName="DB_bookid", initialValue=10000, allocationSize=1)
@Id@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="bookid")
private int BookId;
@Basic@Column(length=50, nullable=false)
private String BookName;
@Basic@Column(length=30, nullable=false)
private String Author;
@Basic@Column(length=30)
private String Subject;
@Basic@Column(length=200, nullable=false)
private String Description;
public int getBookId() {
return BookId;
}
public void setBookId(int bookId) {
BookId = bookId;
}
public String getBookName() {
return BookName;
}
public void setBookName(String bookName) {
BookName = bookName;
}
public String getAuthor() {
return Author;
}
public void setAuthor(String author) {
Author = author;
}
public String getSubject() {
return Subject;
}
public void setSubject(String subject) {
Subject = subject;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}



}

Service class of the same entity is as
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.dev.Entity.Book;

public class BookService {

//Variable Initialization
private EntityManager em = null;
private EntityManagerFactory emf = null;

//Function for Book Persistence
public String bookPersistence(Book book) {
String ret = null;
try{
this.getEntityManager();
em = emf.createEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
em.persist(book);
et.commit();
ret = "Book Persisted";
this.closeEMF();
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
return ret;
}


//Function to assign the Object of Entity Manager
private void getEntityManager() {
emf =Persistence.createEntityManagerFactory("Third");
em = emf.createEntityManager();
}

//Function to Close the EMF Object
private void closeEMF() {
// TODO Auto-generated method stub
emf.close();

}

}


Can you please check the code and let me know where I am committing a mistake. The database that I am using is mysql.