I'm new to ElcipseLink and JPA. I've successfully set up my persistence.xml and EclipseLink library. However, when trying to retrieve data from the server, I get invalid object name: dbo.Material.
My values are stored in the leermiddelen database. The scheme is dbo and the table is Material. When I try to specify the cataloge name (leermiddelen), then I get an error that specifying the database name is not supported in Azure.
A little help? (btw, when manually connection with a connection string and the driver from Microsoft, it does work)
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<class>models.Material</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="javax.persistence.jdbc.url"
value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>
<property name="javax.persistence.jdbc.user" value="xxxxxxxxxxxx"/>
<property name="javax.persistence.jdbc.password" value="xxxxxxxxxx"/>
</properties>
</persistence-unit>
and the java code:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = entityManager.getTransaction();
try {
userTransaction.begin();
#SuppressWarnings("unchecked")
List<Material> materials = entityManager.createQuery("SELECT e from Material e").getResultList();
System.out.println("Getting materials list...");
for (Iterator<Material> iterator = materials.iterator(); iterator.hasNext(); ) {
Material m = (Material) iterator.next();
System.out.println(m.toString());
}
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
entityManager.close();
entityManagerFactory.close();
}
Finally the error:
[EL Warning]: 2016-04-05 11:16:13.426--UnitOfWork(1690796457)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'dbo.Material'.
Error Code: 208
Call: SELECT Number, Amount, CanReserve, Description, Firm, IsAvailable, Name, PhotoUrl, Price FROM dbo.Material
Conclusion for the question. It seems that the issue was caused by the incorrect jdbc url. The jdbc url for Azure SQL Database is as below.
jdbc:sqlserver://<hostname>.database.windows.net:1433;database=<database-name>;user=<username>#<hostname>;password={your_password_here};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
For getting the connection string on Azure portal, please see https://azure.microsoft.com/en-us/documentation/articles/sql-database-develop-java-simple-windows/#step-4-get-connection-string.
Related
I use JPA with Hibernate in my Servlet, which is hosted by Tomcat.
The database I use is MySQL.
I do not use JNDI or a Connection Pool.
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="pixxio-jpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>de.java2enterprise.onlineshop.model.AccessToken</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.88.88:3306/felix1_0"/>
<property name="javax.persistence.jdbc.user" value="felix1_0"/>
<property name="javax.persistence.jdbc.password" value="mypassword"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
This is the important code in my Servlet:
void doubleDatabaseConnection(PrintWriter out) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("pixxio-jpa", null);
EntityManager em = emf.createEntityManager();
EntityManager em2 = emf.createEntityManager();
getDatabaseSessionId(out, em);
getDatabaseSessionId(out, em2);
em.close();
em2.close();
emf.close();
}
void getDatabaseSessionId(PrintWriter out, EntityManager entityManager) {
Query q = entityManager.createNativeQuery("SELECT CONNECTION_ID();");
BigInteger result = (BigInteger) q.getSingleResult();
out.println("<br>Database Session Id: " + result);
}
This is printed by the servlet:
Database Session Id: 51317
Database Session Id: 51317
I assumed that the actual database connection is established, when the EntityManager is created. Therefore I assumed that the two MySQL-Connection-IDs from the two EntityManager instances differ.
Is it possible to create multiple distinct database connections from one EntityManagerFactory instance?
I want to note that changing the JPA provider is an option for me.
Hibernate use the same connection if you do not need a transaction.
If you start a transation, you get a new connection
EntityManagerFactory emf = Persistence.createEntityManagerFactory("pixxio-jpa", null);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
getDatabaseSessionId(System.out, em);
getDatabaseSessionId(System.out, em2);
em.close();
em2.close();
emf.close();
Updated
FYI: Hibernate use it's own connection pool if you do not set an connection pool (min=1; max=20).
when execute this java code,that make select from datastore ,an exception was appeared due to first row,so how i can solve this exception?
exception:
javax.persistence.PersistenceException: Explicit persistence provider error(s) occurred for "transactions-optional" after trying the following discovered implementations: org.datanucleus.api.jpa.PersistenceProviderImpl from provider: org.datanucleus.api.jpa.PersistenceProviderImpl
code:
PrintWriter out = resp.getWriter();
try {
EntityManagerFactory emfactory = Persistence
.createEntityManagerFactory("transactions-optional");
EntityManager entitymanager = emfactory.createEntityManager();
javax.persistence.Query query = entitymanager.createQuery("Select u from test u");
List<test> list = (List<test>) query.getResultList();
out.print(list.size());
} catch (Exception e) {
out.println(e.toString());
} finally {
out.close();
}
persistence.xml:
<persistence-unit name="transactions-optional">
<provider>
org.datanucleus.store.appengine.jpa.DatastorePersistenceProviderImpl
</provider>
<properties>
<property name="datanucleus.NontransactionalRead" value="true" />
<property name="datanucleus.NontransactionalWrite" value="true" />
<property name="datanucleus.ConnectionURL" value="appengine" />
</properties>
</persistence-unit>
</persistence>
As the Exception that you posted in the Comments (!) says
org.datanucleus.metadata.InvalidClassMetaDataException: Class s.follows has application-identity and no objectid-class specified yet has 0 primary key fields. Unable to use SingleFieldIdentity.
Yet you don't post this class (why?! don't you think people may want to see it, when it is what the exception is about?).
Solution : mark a field as #Id just like all JPA docs say to.
So here is what i am trying to achieve:
A Java App with JPA implementation usinf Embedded Derby. Once this is working , i am then planning to have Spark (with Jetty Server) and Angular js.
These are the tools/frameworks i am using
Eclipse IDE (Luna)
Maven Build system
JPA Implementation (EclipseLink)
Embedded Derby for database
Spark with Embedded Jetty server.
Angular JS
I have the persistence.xml defined with the Derby Embedded Driver and the db properties.
In the Main class i am using the EntityManger to get the EM. I also create new Instance of the EmbeddedDerby to start the Engine.
But when i run the App, it says "No Persistence provider Persistence for Entity Manager"named testSparkJettyDerby"
Here's my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="testSparkJettyDerby" transaction-type="RESOURCE_LOCAL">
<class>model.MyUser</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:sample;create=true"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="xxxx"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
</properties>
</persistence-unit>
Code snippet in my Main Class
createConnection();
// TODO Auto-generated method stub
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
private static void createConnection()
{
try
{
Class.forName("org.eclipse.persistence.jpa.PersistenceProvider");
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
if(conn != null) {
System.out.println("Connected...");
}
}
catch (Exception except)
{
except.printStackTrace();
}
}
My derby jar files are in the classpath.
I am not sure if this is possible, but i could not find any tutorial or answers who have done something like this.
Any help is appreciated.
Thanks in advance..
Make sure that your persistence.xml file is in classes(or whatever your build dir is)/META-INF.
I've created a Java adapter in MFP 7.0. The adapter is running on the local development server (Liberty). Since I couldn't find any references in the documentation, is there a possibility to use JPA within the Java adapter to access DB data?
Where do I need to put the persistence.xml?
Is there any configuration I have to do on the Liberty profile server.xml?
Where do I need to put the DB driver's library jar (EclipseLink)?
Attached you'll find the code from the Java adapter:
#GET
public String performJPAQuery(){
String result = null;
Person marco = new Person();
marco.setId(1);
marco.setName("Marco");
// connection details should be loaded from persistence.xml
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-test");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(marco);
tx.commit();
// Querying the contents of the database using JPQL query
Query q = em.createQuery("SELECT p FROM Person p");
#SuppressWarnings("unchecked")
List<Person> results = q.getResultList();
logger.info("List of persons\n----------------");
for (Person p : results) {
logger.info(p.getName() + " (id=" + p.getId() + ")");
}
// Closing connection
em.close();
emf.close();
return result;
}
This is how my persistence.xml looks like:
<?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="jpa-test" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.sample.Person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.sqlite.JDBC" />
<property name="javax.persistence.jdbc.url" value="jdbc:sqlite:sample.db" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
</persistence>
That is definitely possible. The location of the persistence.xml file should be as described here. Besides that, you will have to either:
use the connection using JNDI (in which case you do not need the javax.persistence.jdbc.url parameter).
along to the javax.persistence.jdbc.url parameter put the user credentials to your DB in persistence.xml (if you go for this option google for it, as it depends on the JPA/EclipseLink vesion, but probably this is a good start).
Instantiate manually EVERYTHING, in which case you do not need the persistence.xml file. This option is much more complicated, but also more flexible. I did it with Hibernate once, thus cannot help you with EclipseLink.
I am trying to create a web app using JSF and EJB 3.0.
I am using plain JSF, Glassfish Server, Hibernate as my persistance provider. My database is apache derby.
Here my Stateless Session bean as follows:
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class StudentServiceBean implements StudentService{
#PersistenceContext(unitName="forPractise")
private EntityManager entityMgr;
#Resource
private SessionContext sessionContext;
#Override
public List<StudentVO> fetchStudentListOrderByStudentId(boolean flag){
List<StudentEntity> studentList = null;
TypedQuery<StudentEntity> studentQuery = null;
List<StudentVO> studentVOList = null;
String queryDesc = "select s from StudentEntity s order by s.studentId desc";
String query = "select s from StudentEntity s order by s.studentId";
try{
if(!flag){
studentQuery = entityMgr.createQuery(query,StudentEntity.class);
}else{
studentQuery = entityMgr.createQuery(queryDesc,StudentEntity.class);
}
studentList = studentQuery.getResultList();
studentVOList = new ArrayList<StudentVO>();
for(StudentEntity studentE : studentList){
studentVOList.add(new StudentVO(String.valueOf(studentE.getStudentId()),studentE.getStudentName(),studentE.getContactNumber()));
}
}catch(Exception e){
System.out.println(" EXCEPTION IN "+this.getClass().getName()+" in method fetchStudentListOrderByStudentId "+e);
}
return studentVOList;
}
And this is my persistence.xml:
<?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="forPractise" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/app</jta-data-source>
<class>com.entity.StudentEntity</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
</properties>
</persistence-unit>
</persistence>
What happens is on load of the JSP page, the getter method of StudentList is called -
inside the getter method I have written logic that if studentList is empty then call the studentService.fetchStudentListOrderByStudentId(true);.
But when I do this I get an exception:
EXCEPTION IN com.bb.StudentServiceBean in method
fetchStudentListOrderByStudentId
org.hibernate.service.UnknownServiceException: Unknown service
requested
[org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
Can you please tell me what I am missing, or where I am going wrong?
Thanks.
You indicate that you are using Hibernate 4.x, but the class you mentioned afaik is only valid for JPA 1.0 and Hibernate 3.x. Try removing the following line from your configuration:
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
Just in case it's of any interest, I got this error on Jetty when trying to start a Hibernate session:
Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
The root cause was a previous Exception (a few seconds earlier in the logs) which caused the spring context (WebAppContext) to fail to initialize.
Once I fixed the spring context, the "Unknown service requested" fixed itself. So, if you're seeing this error it's worth checking for earlier errors before investigating too much..