So I have a test set up like this:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.sam.demo.HibernateUtil;
import com.sam.entity.Student;
public class HibernateTest {
private static SessionFactory sessionFactory;
private Session session;
#BeforeAll
public static void setup() {
sessionFactory = HibernateUtil.getSessionFactory();
}
#AfterAll
public static void teardown() {
sessionFactory.close();
}
#BeforeEach
public void openSession() {
session = sessionFactory.getCurrentSession();
}
#AfterEach
public void closeSession() {
session.close();
}
#Test
#DisplayName("Create student in the database")
public void testCreate() {
try {
Student student = new Student("Angela", "Wu", "angelawu#ntu.edu");
session.beginTransaction();
Integer id = (Integer) session.save(student);
session.getTransaction().commit();
Assertions.assertTrue(id > 0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I was running this test after dropping the table manually to see what result I would get. The record could not be inserted into the database because the table did not exist and I got an exception, but I was surprised to see that my test passed! can someone help me with this? I thought that the save() method won't return anything and the id won't be > 0.
My hibernate configuration is:
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/student_tracker?useSSL=false&serverTimezone=UTC
</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.sam.entity.Student" />
</session-factory>
</hibernate-configuration>
You never reached your Assertions.assertTrue(id > 0); statement.
As the db table was missing, commit threw an exception.
You handled the exception by printing the stack trace to the console.
To let the test fail you can:
rethrow the exception
drop the exception handling
Your handler only prints the stack trace, but test runner does the same for uncaught exceptions, so I would go with the latter option.
As a side note, if you need to handle an exception, try to be as specific as possible - catching Exception is rarely a good idea, as it can hide unexpected ones.
Related
I'm trying to get a list of persons using JPA. Every time I run the code, I get "java.lang.IllegalArgumentException: NamedQuery of name: Persoon.getAllePersonen not found."
I tried changing the table name, replaced Persoon.getAllePersonen by getAllePersonen,.... I just can't seem to figure out what's causing the error
Persoon
#Entity
#Table(name = "Persoon")
#NamedQueries({
#NamedQuery(name = "Persoon.getAllePersonen",
query = "SELECT p FROM Persoon p"),
#NamedQuery(name = "Persoon.findByName",
query = "SELECT p FROM Persoon p WHERE p.achternaam = :persoonNaam OR p.voornaam = :persoonNaam")
})
public class Persoon implements Serializable {
PersoonDao
public List<Persoon> getAlleLeden(){
TypedQuery<Persoon> queryP = em.createNamedQuery("Persoon.getAllePersonen", Persoon.class);
try{ return queryP.getResultList();
} catch (NoResultException e){
throw new EntityNotFoundException("Cannot find leden");
}
}
EDIT:
Generic Superclass DAO
public class GenericDaoJpa<T>{
private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaijitanPU");
protected static final EntityManager em = emf.createEntityManager();
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="TaijitanPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>domein.Persoon</class>
<class>domein.Graad</class>
<class>domein.Locatie</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost\sqlexpress:1433;databaseName=Taijitan;integratedSecurity=true;"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
You have to do an abstract class Generic class and override the entityManager of the parent class for each child. Check below. I used EJB Stateless for the childs.
-> PARENT DAO
public abstract class AbstractDAO<T> {
...
protected abstract EntityManager getEntityManager();
-> CHILD DAO
#PersistenceContext(unitName = "yourPersistenceUnitName")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
So ... I just started using databases and my brother recommended me to use H2 with EclipseLink to start. Did a quick Google search and found a Tutuorial:
https://www.javatips.net/blog/eclipselink-jpa-with-h2-database
https://www.javatips.net/blog/java-persistence-jpa-2-0-tutorial-with-eclipselink
If I code it like it is described in the Tutorial i get no error when i run it, but i check the database my Table is still empty. I searched for like a week now but i dont find an answer.
My Code:
Class Student
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENT")
public class Student implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "STUDENTID")
private long studentId;
#Column(name = "STUDENTNAME")
private String studentName;
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public long getStudentId() {
return studentId;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentName() {
return studentName;
}
}
JPAExample
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
public class JPAExample {
private EntityManager entityManager = EntityManagerUtil.getEntityManager();
public static void main(String[] args) {
JPAExample example = new JPAExample();
System.out.println("After Sucessfully insertion ");
Student student1 = example.saveStudent("Sumith");
Student student2 = example.saveStudent("Anoop");
example.listStudent();
System.out.println("After Sucessfully modification ");
example.updateStudent(student1.getStudentId(), "Sumith Honai");
example.updateStudent(student2.getStudentId(), "Anoop Pavanai");
example.listStudent();
System.out.println("After Sucessfully deletion ");
example.deleteStudent(student2.getStudentId());
example.listStudent();
}
public Student saveStudent(String studentName) {
Student student = new Student();
try {
entityManager.getTransaction().begin();
student.setStudentName(studentName);
student = entityManager.merge(student);
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
return student;
}
public void listStudent() {
try {
entityManager.getTransaction().begin();
#SuppressWarnings("unchecked")
List<Student> Students = entityManager.createQuery("from Student").getResultList();
for (Iterator<Student> iterator = Students.iterator(); iterator.hasNext();) {
Student student = (Student) iterator.next();
System.out.println(student.getStudentName());
}
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
public void updateStudent(Long studentId, String studentName) {
try {
entityManager.getTransaction().begin();
Student student = (Student) entityManager.find(Student.class, studentId);
student.setStudentName(studentName);
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
public void deleteStudent(Long studentId) {
try {
entityManager.getTransaction().begin();
Student student = (Student) entityManager.find(Student.class, studentId);
entityManager.remove(student);
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
}
EntityManagerUtil
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerUtil {
private static final EntityManagerFactory entityManagerFactory;
static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("test");
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManager getEntityManager() {
return entityManagerFactory.createEntityManager();
}
}
Persistence.xml
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
<class>Student</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
When i run the JPAExample i get this output:
My Output
But the expected Output should look like this:
Expected Output
And if i look into the H2 Database nothing has changed:
H2 Database Interface (German Language)
Hope someone can help me or can link me a usefull/better JPA Tutorial :)
You are catching exceptions but not acknowledging or logging them - you should make sure you at least log it.
In this case, your listStudent method is getting an exception on
entityManager.createQuery("from Student").getResultList()
as this is an invalid JPQL query. You should be using something like:
entityManager.createQuery("select s from Student s").getResultList()
I want to run different classes particular method from TestNG but everytime it opens a new window when i include beforeclass in each class so i have now excluded beforeclass from add and logout classes so it can use same browser to run rest methods but its not working
The first class is of login class which is as below
public class LoginWeb {
public WebDriver driver;
WebDriverWait wait;
LoginScreen loginExcel;
#BeforeClass
public void beforeClass (){
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://10.7.1.180/views/index.html#/login");
System.out.println(driver.getTitle());
}
#Test (description = "Valid Credentials!")
public void LoginWithValidWebExcelEmailAndPass() throws IOException, BiffException {
loginExcel= new LoginScreen(driver);
FileInputStream fi = new FileInputStream("D:\\Programs\\New\\Sourcesmartdata.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
int z = s.getRows();
System.out.println("no of rows------------------------:"+z);
String email = s.getCell(0, 1).getContents();
System.out.println("Email -----------------"+email);
loginExcel.EnterEmail(email);
String password= s.getCell(1, 1).getContents();
System.out.println("Password------------------- "+password);
loginExcel.EnterPassword(password);
loginExcel.ClickToLogin();
wait= new WebDriverWait(driver, 10);
WebElement GetLogo = wait.until(ExpectedConditions.visibilityOf(loginExcel.TopRightMenu));
String str= GetLogo.getText();
System.out.println("Text------------"+str);
Assert.assertEquals(str, "Source Smart");
}
}
The second class is of adding commodities here i have excluded beforeclass as if i include before class it opens a new window and here login script is not written
public class AddCommoditiesWeb{
WebDriver driver;
WebDriverWait wait;
AddCommodities addcommodity;
#Test (description="Add Multiple Commodities!")
public void AddMultipleNewCommodities () throws Exception, Exception{
addcommodity = new AddCommodities(driver);
addcommodity.MenuCommodities(); //click left menu to open manage commodities page
FileInputStream fi = new FileInputStream("D:\\Programs\\New\\Sourcesmartdata.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(1);
int z=s.getRows();
System.out.println("no of rows------------------------:"+z);
for(int row=1; row <2; row++){
Thread.sleep(5000);
addcommodity.ClickAddCommodities(); // click add commodity button
String commodityname = s.getCell(0, row).getContents();
System.out.println("commodityname -----------------"+commodityname);
//enterdefinecommodityTxtBox.sendKeys(commodityname);
addcommodity.Enterdefinecommodity(commodityname);
String grade= s.getCell(1, row).getContents();
System.out.println("grade------------------- "+grade);
//entergradeTxtBox.sendKeys(grade);
String unit= s.getCell(2, row).getContents();
System.out.println("unit------------------- "+unit);
//enterunitTxtBox.sendKeys(unit);
String minprice= s.getCell(3, row).getContents();
System.out.println("min price------------------- "+minprice);
//enterminpriceTxtBox.sendKeys(minprice);
String maxprice= s.getCell(4, row).getContents();
System.out.println("max price------------------- "+maxprice);
//entermaxpriceTxtBox.sendKeys(maxprice);
addcommodity.EnterAddCommoditiesData(grade,unit,minprice,maxprice);
}
wait=new WebDriverWait(driver,10);
WebElement commodityname= wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/div[4]/div/section[2]/div[4]/d-expand-collapse[1]/div/div/div[1]/h4/a")));
String commoditynamejustadded= commodityname.getText();
System.out.println("name--------------"+commoditynamejustadded);
assertEquals(commoditynamejustadded, "Rice");
}
}
TestNG code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Login check">
<classes>
<class name="SourceSmartWeb.LoginWeb"/>
<class name = "SourceSmartWeb.AddCommoditiesWeb">
<methods>
<include name="AddMultipleNewCommodities"/>
</methods>
</class>
<class name ="SourceSmartWeb.LogoutWeb"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Logout class:
public class LogoutWeb{
WebDriver driver;
// #BeforeClass
// public void beforeClass (){
// System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
// driver=new ChromeDriver();
// driver.manage().window().maximize();
// driver.get("http://10.7.1.180/views/index.html#/login");
// System.out.println(driver.getTitle());
// super.beforeClass();
//
// }
#Test
public void Logout() throws InterruptedException {
LogoutScreen logout=new LogoutScreen(driver);
logout.ClickToLogout();
}
#AfterClass
public void exit(){
driver.quit();
}
}
What its doing is it opens the browser logins and then do nothing. How can i make it do rest of activities on same browser as if i add before class in second class it opens a new browser and then there i dont have login code. please guide
From what you are stating, it looks like you need to basically have a browser spawned per <test> tag and then share that browser amongst all your test classes. But you cannot make use of the #BeforeTest and #AfterTest annotations because you would need to bring in inheritance into the picture and since these methods are executed only once per <test> you will start seeing NullPointerException.
So the idea is to basically leverage TestNG listeners for this webdriver instantiation and cleanup and have your test classes/methods just query them from within a helper method.
Here's some sample code, that shows all of this in action.
Here's how the listener would look like
package com.rationaleemotions.stackoverflow.qn46239358;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
public class WebdriverSpawner extends TestListenerAdapter {
private static final String WEBDRIVER = "webdriver";
#Override
public void onStart(ITestContext testContext) {
testContext.setAttribute(WEBDRIVER, createDriver());
}
#Override
public void onFinish(ITestContext testContext) {
getWebDriverFromContext(testContext).quit();
}
public static RemoteWebDriver getCurrentWebDriver() {
ITestResult result = Reporter.getCurrentTestResult();
if (result == null) {
throw new IllegalStateException("Please invoke this from within a #Test annotated method");
}
ITestContext context = result.getTestContext();
return getWebDriverFromContext(context);
}
private static RemoteWebDriver getWebDriverFromContext(ITestContext context) {
Object object = context.getAttribute(WEBDRIVER);
if (!(object instanceof RemoteWebDriver)) {
throw new IllegalStateException("Encountered problems in retrieving the webdriver instance");
}
return (RemoteWebDriver) object;
}
private static RemoteWebDriver createDriver() {
return new ChromeDriver();
}
}
Here's how your test classes which now use this above listener can look like (I have intentionally kept it simple and have it open up just a URL, but if you run them you would notice a single browser opening up multiple URLs. So only one browser instance)
package com.rationaleemotions.stackoverflow.qn46239358;
import org.testng.annotations.Test;
public class LoginWeb {
#Test(description = "Valid Credentials!")
public void LoginWithValidWebExcelEmailAndPass() {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.google.com"));
}
}
package com.rationaleemotions.stackoverflow.qn46239358;
import org.testng.annotations.Test;
public class LogoutWeb {
#Test
public void Logout() throws InterruptedException {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.facebook.com"));
}
}
package com.rationaleemotions.stackoverflow.qn46239358;
import org.testng.annotations.Test;
public class AddCommoditiesWeb {
#Test(description = "Add Multiple Commodities!")
public void AddMultipleNewCommodities() {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.yahoo.com"));
}
#Test
public void anotherTestMethod() {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.ndtv.com"));
}
}
The PageLoader utility class looks like this
package com.rationaleemotions.stackoverflow.qn46239358;
import org.openqa.selenium.remote.RemoteWebDriver;
public final class PageLoader {
private PageLoader() {
//Utility class defeat instantiation
}
public static String loadAndGetTitle(String url) {
RemoteWebDriver driver = WebdriverSpawner.getCurrentWebDriver();
driver.get(url);
return driver.getTitle();
}
}
Here's how the suite xml looks like :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="46216357_Suite" verbose="2">
<listeners>
<listener class-name="com.rationaleemotions.stackoverflow.qn46239358.WebdriverSpawner"/>
</listeners>
<test name="Login_check">
<classes>
<class name="com.rationaleemotions.stackoverflow.qn46239358.LoginWeb"/>
<class name="com.rationaleemotions.stackoverflow.qn46239358.AddCommoditiesWeb">
<methods>
<include name="AddMultipleNewCommodities"/>
</methods>
</class>
<class name="com.rationaleemotions.stackoverflow.qn46239358.LogoutWeb"/>
</classes>
</test>
</suite>
So here none of your #Test classes invoke driver.quit() explicitly. The webdriver cleanup is managed by the listener.
This model is going to work only when you want to run multiple tests on the same browser.
The flip side of this would be that, you can NEVER run your #Test methods in parallel, because now all your tests are sharing the same browser.
ow can I filter using multiple attributes? (simulating an "AND"
operation)
I have tried:
ofy().load().type(Produit.class).filter("idListe in",collectionProduits.getIdListes()).filter("supprime !=",true).list();
This is my entity:
#Entity
public class Produit implements Serializable{
private static final long serialVersionUID = xxxxxxxxxxxxxx;
#Id
private Long id;
#Index
private Long idliste;
#Index
private Boolean supprime;
public Produit() {
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIdliste() {
return idliste;
}
public void setIdliste(Long idliste) {
this.idliste = idliste;
}
public Boolean getSupprime() {
return supprime;
}
public void setSupprime(Boolean supprime) {
this.supprime = supprime;
}
I have this critical error:
Uncaught exception from servlet java.io.IOException:
com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException:
no matching index found. The suggested index for this query is:
<datastore-index kind="Produit" ancestor="false" source="manual">
<property name="idliste" direction="asc"/>
<property name="supprime" direction="asc"/>
</datastore-index>
(through reference chain:
com.listecourses.model.CollectionProduits["produits"]) at
com.google.api.server.spi.response.ServletResponseResultWriter.writeValueAsString(ServletResponseResultWriter.java:187)
at
com.google.api.server.spi.response.ServletResponseResultWriter.write(ServletResponseResultWriter.java:74)
at
....
After seeing this error, I changed my datastore-indexes.xml to this:
<?xml version="1.0" encoding="utf-8"?>
<datastore-indexes autoGenerate="false">
<datastore-index kind="Produit" ancestor="false" source="manual">
<property name="idliste" direction="asc"/>
<property name="supprime" direction="asc"/>
</datastore-index>
</datastore-indexes>
I re-deployed after creating this file. I waited a little bit of time for the index to generate. And I have the same error on log of appengine.
more, I have this error log on eclipse:
No projects found for [C:\workspace\example-AppEngine\war\datastore-indexes.xml]
I have an Android project and an app engine connected project. I am using the following:
JPA v2,
App Engine 1.7.6,
Java 1.7 compiler,
Eclipse 4.2 Juno,
EclipseLink 2.4.x
I am using Cloud sql db. I am able to connect successfully in the JPA and DB Persective window and query data back ok. I have set up my app engine to have the SQL Development to be connected to my CLOUD Sql db.
I have one table defined as follows:
CREATE Table Test(codeid varchar(3) NOT NULL,codedesc varchar(20) NOT NULL,PRIMARY KEY (codeid));
The Entity class is as follows:
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Test implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String codeid;
private String codedesc;
public Test() {
}
public String getCodeid() {
return this.codeid;
}
public void setCodeid(String codeid) {
this.codeid = codeid;
}
public String getCodedesc() {
return this.codedesc;
}
public void setCodedesc(String codedesc) {
this.codedesc = codedesc;
}
}
the endpoint class is as follows:
#Api(name = "testendpoint" , version = "v1")
public class TestEndpoint {
/**
* This method lists all the entities inserted in datastore.
* It uses HTTP GET method and paging support.
*
* #return A CollectionResponse class containing the list of all entities
* persisted and a cursor to the next page.
*/
#ApiMethod( httpMethod = "GET", name = "listtest.list", path = "ch/list")
#SuppressWarnings({ "unchecked", "unused" })
public CollectionResponse<Test> listTest(
#Nullable #Named("cursor") String cursorString,
#Nullable #Named("limit") Integer limit) {
EntityManager mgr = null;
Cursor cursor = null;
List<Test> execute = null;
try {
mgr = getEntityManager();
Query query = mgr.createQuery("select x from Test x");
if (cursorString != null && cursorString != "") {
cursor = Cursor.fromWebSafeString(cursorString);
query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
}
if (limit != null) {
query.setFirstResult(0);
query.setMaxResults(limit);
}
execute = (List<Test>) query.getResultList();
cursor = JPACursorHelper.getCursor(execute);
if (cursor != null)
cursorString = cursor.toWebSafeString();
// Tight loop for fetching all entities from datastore and accomodate
// for lazy fetch.
for (Test obj : execute);
}
finally
{
mgr.close();
}
return CollectionResponse.<Test> builder().setItems(execute).setNextPageToken (cursorString).build();
}
private boolean containsCodeheader(Test test) {
EntityManager mgr = getEntityManager();
boolean contains = true;
try {
Test item = mgr
.find(Test.class, test.getCodeid());
if (item == null) {
contains = false;
}
} finally {
mgr.close();
}
return contains;
}
private static EntityManager getEntityManager() {
return EMF.get().createEntityManager();
}
}
persistence.xml looks 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="transactions-optional" transaction-type="RESOURCE_LOCAL">
<provider></provider>
<class>com.testApp.Test</class>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
What I am trying to do is run my endpoint to get a list of records back . I When I run the following I dont get any errors in the console.
localhost:8888/_ah/api/testendpoint/v1/ch/list
I get the follwoing in the Google Chrome when I know there are records in my table.
{
"items" : [ ]
}
Please let me know if you need more info.
I have carried out further testing and found my above example works for another test app engine project I created before from scratch. A difference I have found is, when I run the broken app engine locally I get the following warning in the Console window which I dont in the working test app:
The backing store, \war\WEB-INF\appengine-generated\local_db.bin, does not exist. It will be created.
Well I am happy to report that I found the answer to this issue. Turns out I was doing everything correctly. The only thing I had to do was take the following line out of persistence.xml file:
<property name="datanucleus.ConnectionURL" value="appengine"/>
I already had the following set in the file:
<property name="javax.persistence.jdbc.driver" value="com.google.appengine.api.rdbms.AppEngineDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms://Your db connection/databasename"/>.