I am fairly new to Wildfly and really new to JPA. I get a null exception when I try to call a method from the DAO. I made some changes suggested using the #Stateless and #Inject annotations, but the DAO does not appear to be initializing at all. The object is null when I try to call the findAllClientCompanies method.
Here is the peristence.xml file.
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="miscPU">
<jta-data-source>java:/jdbc/misc</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="autojobsPU">
<jta-data-source>java:/jdbc/autojobs</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
</properties>
</persistence-unit>
</persistence>
Here is the entity declaration:
#Entity
#Table(name="clientcompany")
public class ClientCompany extends Company implements Serializable {
Here is the dao, the findAllClientCompanies is the specific method that is blowing up with a null exception:
package com.lingosys.jpa;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;
/**
*
* #author mphoenix
*/
#Stateless
public class ClientCompanyDAO implements Serializable {
#PersistenceContext(unitName="miscPU")
private EntityManager em;
public ClientCompanyDAO() {
}
public void create(ClientCompany clientCompany) {
em.persist(clientCompany);
}
public EntityTransaction getTransaction() {
return em.getTransaction();
}
public ClientCompany findClientCompany(int id) {
ClientCompany clientCompany = (ClientCompany) em.find(ClientCompany.class, id);
return clientCompany;
}
public List <ClientCompany> findAllClientCompanies() {
TypedQuery<ClientCompany> query = em.createQuery("select c from ClientCompany c", ClientCompany.class);
return query.getResultList();
}
public void delete(ClientCompany clientCompany) {
em.remove(em.contains(clientCompany) ? clientCompany:em.merge(clientCompany));
}
public int deleteAllClientCompanies() {
Query query = em.createQuery("delete from ClientCompany");
return query.executeUpdate();
}
}
And here is the JSF bean that calls the dao method:
#Inject
private ClientCompanyDAO daoClientCompany;
private boolean noValidEmail = false;
private String fakeEmailUserName = "";
private Connection conn;
private List<ClientCompany> unsortedList;
private String specialInstructions;
private String createdBy;
//XML processing variables
private Document document = null;
private String xmlMsgs = "";
private boolean xmlLoaderDisabled = false;
//prospect handling variables
private boolean prospectDisabled = false;
private static final String YES = "Yes";
//Legal entity based variables
boolean entitySet = false;
boolean lls = false;
boolean clientIDSet = false;
boolean billingInstructionsSet = false;
boolean billingEmailSet = false;
private static final String[] IS_LLS = {"LLS", "Coto/TI", "LLS-UK"};
boolean companyLoggedOn = false;
private boolean processDisabled = true;
private boolean userSpecificEntity = false;
/**
* Constructor initializes Web Service client, Hibernate DAOs, UI lists, and
* client view.
*
*/
public ClientCreatorBean() {
fmrws = new FormerWSOps();
try {
unsortedList = daoClientCompany.findAllClientCompanies();
view = fmrws.getClientCompanyView();
} catch (Exception ex) {
java.util.logging.Logger.getLogger(ClientCreatorBean.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
reset();
OK it looks like this problem had to do with my invoking the DAO in my constructor. I resolved it by putting the code in another method and prefacing that method with the #PostConstructor annotation.
I want to put POJO bean key value pair to Ignite cache using REST API. I can put string key value pair to cache. but here i want to put a class as key value. How can i create REST url for this.
My config file look like this
<property name="cacheConfiguration">
<bean class="org.apache.ignite.configuration.CacheConfiguration">
<!-- Set a cache name. -->
<property name="name" value="cacheName"/>
<!-- Set cache mode. -->
<property name="cacheMode" value="PARTITIONED"/>
<property name="indexedTypes">
<list>
<value>com.test.EntitlementKey</value>
<value>com.test.Entitlement</value>
</list>
</property>
</bean>
</property>
And Entitilement Class look like this
import org.apache.ignite.cache.query.annotations.QuerySqlField;
public class Entitlement {
#QuerySqlField
private String name;
#QuerySqlField
private String desc;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getdesc() {
return desc;
}
public void setdesc(String desc) {
this.desc = desc;
}
And EntitlementKey class
public class EntitlementKey {
#QuerySqlField(index = true)
private String eid;
#QuerySqlField
private String id;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public String getid() {
return id;
}
public void setid(String id) {
this.id = id;
}
Currently, in master, you can find an implementation of ticket, which allows using internal java types as keys and values.
At this moment if you want to use your custom types, you need to use ConnectorMessageInterceptor interface. Once you implement and configure it, you will start receiving a callback for all keys and values passed back and forth. So you can encode your object as a String somehow and then convert it to a real object inside interceptor. And the opposite: before returning object from the cache you can convert it to some String form.
I am trying to learn MongoDB and in the same time write a simple REST application using Spring framework.
I have a simple model:
#Document
public class Permission extends documentBase{
#Indexed(unique = true)
private String name;
public Permission(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then I have a simple DAO:
#Repository
#Transactional
#Profile({"production","repositoryTest","mongoIntegrationTest"})
public class DaoImpl implements DAO {
#Autowired
protected MongoTemplate mongoTemplate;
public <T> T addObject(T object) {
mongoTemplate.insert(object);
return object;
}
The I have my integration tests:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:mvc-dispatcher-servlet.xml", classpath:IntegrationContext.xml"},loader = TestXmlContextLoader.class)
#ActiveProfiles("mongoIntegrationTest")
public class RepositoryIntegrationTest extends AccountTestBase{
#Autowired DAO repository;
#Autowired WebApplicationContext wac;
#Test
public void AddPermission() {
Permission permission_1 = new Permission("test");
Permission permission_2 = new Permission("test");
repository.addObject(permission_1);
repository.addObject(permission_2);
}
}
My configuration:
<!-- MongoDB host -->
<mongo:mongo host="${mongo.host.name}" port="${mongo.host.port}"/>
<!-- Template for performing MongoDB operations -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"
c:mongo-ref="mongo" c:databaseName="${mongo.db.name}"/>
I am expecting that, on adding "permission_2" their would be a exception thrown from MongoDB, which would be translated by Spring,, and catched as a DataAccessException in the DAO.
Looking at the log files from MongoDb I can see that a duplicated exception is thrown but it never reaches my DAO.
So,, I guess I am doing something wrong,,, but at the moment,, I am blind to my own misstakes.
//lg
Make sure you configure the WriteConcern of the MongoTemplate to something non-default (e.g. WriteConcern.SAFE). By default MongoDB is in fire-and-forget mode and does not throw exceptions on index violations or server errors in general.
Still struggling with this.
Finnally I succeded to get the exeption translation working. MongoDb throws a exception which is translated to Spring Data exception.
Now I am stuck with another problem.
My DAO shown above has also the following code:
#ExceptionHandler(DataAccessException.class)
public void handleDataAccessException(DataAccessException ex) {
// For debug only
DataAccessException test = ex;
test.printStackTrace();
}
I was expecting this code to catch the exception thrown,, but this is not the case.
Why not?
//lasse
I'm using eclipse JPA project to create entities in Apache Derby. I'm using the JPA Tools:
"generate tables from entities.."
command. When I use this command, the tables are put into the database. I can see the tables, and that they have columns from the Eclipse "Data Source Explorer". When I log in to Derby through ij.
I type:
'show tables in schema x';
I get a list of the table names that correspond to the entities.
I type:
'select * from <table in x>'
I get:
ERROR 42X05: Table/View 'ADDRESS' does not exist.
Why do my tables not stick..? When I use the CREATE TABLE commands that are being entered in during use of the "generate tables from entities.." command, they produce tables there. When I type 'select * .." I get a table.
Second, probably related problem. I have a class. I use the following commands to obtain an entity manager:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DataModelAccess");
EntityManager em = emf.createEntityManager();
If I run a test on my entities, such as this:
public void runTest()
{
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("DataModelAccess");
EntityManager em = emf.createEntityManager();
System.out.println(emf == null);
Address address = new Address();
address.setAddressID("1");
address.setAddressNumber(1746);
address.setStreetName("Howard");
address.setStreetType("Court");
address.setCity("Lennyville");
address.setState("CT");
address.setZipcode(73625);
em.persist(address);
em.close();
emf.close();
// reassign:
emf = Persistence.createEntityManagerFactory("DataModelAccess");
em = emf.createEntityManager();
Address address2 = em.find(Address.class, "1");
System.out.println(address2.getCity());
I get a NullPointerException on the last line.
If I do not re-assign to emf and em, It will print the city to the console.
So,
1. Why do tables not appear for SELECT * FROM <TABLE_NAME>?
But do appear for SHOW TABLES IN <SCHEMA>?
2. Why is my data not persistent across sessions?
I'm running this in Eclipse, from a plain old Java SE object. There is no Java EE container. It's an Eclipse JPA project. There is a persistence.xml file. There is a connection called 'derby' that is managed by eclipse. Maybe I have a persistence.xml file problem? Maybe this is a common problem for everyone. Maybe JPA and eclipselink do this by default because of some differing access protocol? Maybe not having a Java EE Container is making it difficult?
========
As requested:
the address class is totally irrelevant. I've tried both field and property based access also. It makes no difference to IJ. Both attempts fail equally well. This is a summary:
#Entity
#Table(name="ADDRESS")
public class Address
implements Serializable
...
#Id
public String getAddressID()
every thing else is fields, constructor, getters and setters. No annotations. I just added a new JPA entity by right-clicking on my package and selecting
New --> JPA Entity
I put the fields in it using the eclipse wizard. I made it property-based. I thought maybe field-based access would change things, so I tried field-based, but it made no difference.
where you see this: address.setStreetName("Howard");
there is the field:
private String streetName;
and two corresponding methods
setStreetName(String x);
and
String getStreetName();
The same formula exists for all fields in the class. Each field has a getter and a setter. There are no more methods than the getters and the setters. 1 field per each getter/setter method pair. There are no more annotations than I mentioned.
Just for information: I do not set all of the properties for the Address class. The fields in the table were all entered into the database as NULLABLE. Yet, IJ does not find any TABLE. – user1405870 11 hours ago
=========
Here's the Address and Address_ classes:
package dataAccess.customer;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="Dali", date="2012-05-18T21:44:02.229-0500")
#StaticMetamodel(Address.class)
public class Address_
{
public static volatile SingularAttribute<Address, String> addressID;
public static volatile SingularAttribute<Address, Integer> addressNumber;
public static volatile SingularAttribute<Address, String> streetName;
public static volatile SingularAttribute<Address, String> streetType;
public static volatile SingularAttribute<Address, String> building;
public static volatile SingularAttribute<Address, String> floor;
public static volatile SingularAttribute<Address, String> unit;
public static volatile SingularAttribute<Address, String> landmarkName;
public static volatile SingularAttribute<Address, String> city;
public static volatile SingularAttribute<Address, String> state;
public static volatile SingularAttribute<Address, Integer> zipcode;
}
package dataAccess.customer;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Address
*
*/
#Entity
#Table(name="ADDRESS")
public class Address
implements Serializable
{
private String addressID;
private Integer addressNumber;
private String streetName;
private String streetType;
private String building;
private String floor;
private String unit;
private String landmarkName;
private String city;
private String state;
private Integer zipcode;
private static final long serialVersionUID = 1L;
public Address()
{
}
#Id
public String getAddressID()
{
return addressID;
}
public void setAddressID(String addressID)
{
this.addressID = addressID;
}
public Integer getAddressNumber()
{
return this.addressNumber;
}
public void setAddressNumber(Integer addressNumber)
{
this.addressNumber = addressNumber;
}
public String getStreetName()
{
return this.streetName;
}
public void setStreetName(String streetName)
{
this.streetName = streetName;
}
public String getStreetType()
{
return this.streetType;
}
public void setStreetType(String streetType)
{
this.streetType = streetType;
}
public String getBuilding()
{
return this.building;
}
public void setBuilding(String building)
{
this.building = building;
}
public String getFloor()
{
return this.floor;
}
public void setFloor(String floor)
{
this.floor = floor;
}
public String getUnit()
{
return this.unit;
}
public void setUnit(String unit)
{
this.unit = unit;
}
public String getLandmarkName()
{
return this.landmarkName;
}
public void setLandmarkName(String landmarkName)
{
this.landmarkName = landmarkName;
}
public String getCity()
{
return this.city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return this.state;
}
public void setState(String state)
{
this.state = state;
}
public Integer getZipcode()
{
return this.zipcode;
}
public void setZipcode(Integer zipcode)
{
this.zipcode = zipcode;
}
}
Here's the 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="DataModelAccess" transaction-type="RESOURCE_LOCAL">
<class>dataAccess.customer.Person</class>
<class>dataAccess.customer.Address</class>
<class>dataAccess.customer.PhoneNumber</class>
<class>dataAccess.customer.Customer</class>
<class>dataAccess.customer.TwoFieldTest</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation.output-mode" value="database"></property>
<property name="eclipselink.target-database" value="derby"/>
<property name="eclipselink.target-server" value="None"/>
<property name="eclipselink.exclude-eclipselink-orm" value="true"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.jdbc.cache-statements" value="true"/>
<property name="eclipselink.jdbc.native-sql" value="true"/>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/sample;create=true"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="eclipselink.jdbc.bind-parameters" value="false"/>
<property name="eclipselink.jdbc.exclusive-connection.mode" value="Transactional"/>
<property name="eclipselink.orm.validate.schema" value="true"/>
<property name="eclipselink.orm.throw.exceptions" value="true"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
Comments:
calling
em.flush();
is exactly what I did, in order to check if the data was persisting across sessions (which it does not). In other words, when I run the method "runTest()" I get the correct print statements, under the original runTest() method. I have posted the altered "runTest()" method (see the: //reassign "comment"). Now, when I have a customer, which I build out of three entities: address, phoneNumber, and, person, the customer can instantiated through finding the other three entities "in the database", with the entity manager. However, if I comment out everything, except for the code that looks up the three entities in the database and creates a new customer, then I find that I cannot get the data out of the database.
that looks like this:
Customer c = new Customer();
c.setAddress(em.find(Address.class, "1"));
c.setPhoneNumber(em.find(PhoneNumber.class, "1"));
c.setName(em.find(Person.class, "1"));
c.setCustomerID("123");
em.persist(c);
*/
Customer actual = em.find(Customer.class, "123");
and when I comment out everything until after em.persist(c), I do not get any Customer actual.
normally, I get this:
Customer:
Name:
Mr. Howard T Stewart III
Address:
1746 Howard Court
Lennyville, CT 73625
Phone:
(215) 256-4563
But when I comment out everything until
Customer actual = em.find(Customer.class, "123");
(now.. I instantiated the em in a previous line, but I did not now create person, phone_number, or address.)
Then, .. I get,
(actual == null)
evaluates to true.
Am I misusing the "find()" command? Am I supposed to do something else to load a current connection to the database or something (in terms of commands through em (em.method())?
Remember that there is no Java EE container here. I'm just doing this in eclipse, running main methods in j2se programs, in a JPA project in eclipse, using eclipselink 2.3. But this is not EJB, nor is it ManagedBeans or etc.
So..
I found this:
#Resource
UserTransaction utx;
...
try {
utx.begin();
bookDBAO.buyBooks(cart);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception exe) {
System.out.println("Rollback failed: "+exe.getMessage());
}
...
Unfortunately, I didn't find anything about UserTransaction until I got to the Web portion of the java ee tutorial, so, as such, I was unable to find the sentence that said "user transaction" amidst all the implication that em.persist() is all that it takes. Also, #Resource might not work outside of a Java EE Container.
Daniel: thank you for the comment, it gave me the answer that I needed.
Even though I had found the above items, and although I was doing this:
em.getTransaction().begin();
// .. set fields of address ..
em.persist(address);
em.getTransaction().commit();
em.close();
It still wasn't working. When I changed the persistence.xml file to only CREATE tables, the test method runs correctly, and, when I comment out everything but retrieve the customer from the database, that returns correctly as well.
I have also tried:
SELECT * FROM <SCHEMA>.ADDRESS;
and that works fine as well. Thank you so much, as finding out what the entity manager is actually doing because of the "DROP AND CREATE TABLES" directive would likely be a very hard thing to track down amongst tutorials.
In your persistence.xml you have,
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
This means every time you create a new EntityManagerFactory you will recreate your database, loosing all of the data.
Either remove this, or change it to "create-tables" to only create.
For your first issue, try ., i.e. x.address
since you are using Eclipselink JPA, it will not follow standard syntax of SQL query if you are using standard "createQuery" method
You need to use this:
select t from table1 t
instead of
select * from table1
It follows syntax of JPQL. See this link for more info.
But if you want to use native sql method, use "createNativeMethod" from manager instance
I want to build a minimalistic local app that reads/writes HBase via JPA2 without orm.xml and without maven2.
Thereby I use Eclipse with the DataNucleus Plugin whose Enhancer is enabled for the project.
Inspired by
http://matthiaswessendorf.wordpress.com/2010/03/17/apache-hadoop-hbase-plays-nice-with-jpa/
I got the following Entities:
#Entity
#Table(name="account_table")
public class Account
{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
String firstName = null;
String lastName = null;
int level = 0;
#Embedded
Login login = null;
public Account() { }
public Account(String firstName, String lastName, int level, Login login) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.level = level;
this.login = login;
}
and
#Embeddable
public class Login
{
private String login = null;
private String password = null;
public Login() {
// TODO Auto-generated constructor stub
}
public Login(String login, String password) {
super();
this.login = login;
this.password = password;
}
}
The src/META-INF/persistence.xml
<persistence
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
−
<persistence-unit name="hbase-addressbook"
transaction-type="RESOURCE_LOCAL">
<class>de.syrtec.jpa2hbase.entities.Login</class>
<class>de.syrtec.jpa2hbase.entities.Account</class>
<properties>
<property name="datanucleus.ConnectionURL" value="hbase" />
<property name="datanucleus.ConnectionUserName" value="" />
<property name="datanucleus.ConnectionPassword" value="" />
<property name="datanucleus.autoCreateSchema" value="true" />
<property name="datanucleus.validateTables" value="false" />
<property name="datanucleus.Optimistic" value="false" />
<property name="datanucleus.validateConstraints" value="false" />
</properties>
</persistence-unit>
</persistence>
the DAO:
public class TestDAO {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase-addressbook");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
Account a1 = new Account("myPre", "mySur", 1, new Login("a", "b"));
tx = em.getTransaction();
tx.begin();
em.persist(a1);
tx.commit();
}
}
But when first line of the test DAO is executed...
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase-addressbook");
..I get:
11/09/01 06:57:05 INFO DataNucleus.MetaData: Class "de.syrtec.jpa2hbase.entities.Account" has been specified with JPA annotations so using those.
11/09/01 06:57:05 INFO DataNucleus.MetaData: Class "de.syrtec.jpa2hbase.entities.Login" has been specified with JPA annotations so using those.
Exception in thread "main" javax.persistence.PersistenceException: Explicit persistence provider error(s) occurred for "hbase-addressbook" after trying the following discovered implementations: org.datanucleus.api.jpa.PersistenceProviderImpl from provider: org.datanucleus.api.jpa.PersistenceProviderImpl
at javax.persistence.Persistence.createPersistenceException(Persistence.java:242)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:184)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:70)
at de.syrtec.jpa2hbase.start.TestDAO.main(TestDAO.java:15)
Caused by: org.datanucleus.exceptions.NucleusUserException: Errors were encountered when loading the MetaData for the persistence-unit "hbase-addressbook". See the nested exceptions for details
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:879)
at org.datanucleus.api.jpa.JPAEntityManagerFactory.initialiseNucleusContext(JPAEntityManagerFactory.java:745)
at org.datanucleus.api.jpa.JPAEntityManagerFactory.<init>(JPAEntityManagerFactory.java:422)
at org.datanucleus.api.jpa.PersistenceProviderImpl.createEntityManagerFactory(PersistenceProviderImpl.java:91)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:150)
... 2 more
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "−
de.syrtec.jpa2hbase.entities.Login" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:247)
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:412)
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:859)
... 6 more
Before I ran the DAO I triggered class enhancing by datanucleus succesfully:
DataNucleus Enhancer (version 3.0.0.release) : Enhancement of classes
DataNucleus Enhancer completed with success for 2 classes. Timings : input=623 ms, enhance=101 ms, total=724 ms. Consult the log for full details
Although I don't understand that enhancing isn't triggered automatically (referring to the logs) despite of having auto-enhancement for the project activated..
Does anybody know why my entities aren't found?
And that minus sign in persistence.xml ?