GAE : Google Cloud SQL + JPA is not working - jpa

When i connected my cloud sql instance with JPA using EclipseLink 2.2.1, it shows following error
W 2012-10-24 12:21:46.120
org.datanucleus.metadata.xml.AbstractMetaDataHandler error: MetaData Parser encountered an error in file "file:/base/data/home/apps/s~appengineaplicationID/8.362672796318745816/WEB-INF/classes/META-INF/persistence.xml" at line 2, column 248 : cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'. - Please check your specification of DTD and the validity of the MetaData XML that you have specified.
W 2012-10-24 12:21:46.885
Error for /jpatest
java.lang.ExceptionInInitializerError
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
Caused by: org.datanucleus.exceptions.NucleusUserException: No available StoreManager found for the datastore URL key "". Please make sure you have all relevant plugins in the CLASSPATH (e.g datanucleus-rdbms?, datanucleus-db4o?), and consider setting the persistence property "datanucleus.storeManagerType" to the type of store you are using e.g rdbms, db4o
W 2012-10-24 12:21:46.887
Nested in java.lang.ExceptionInInitializerError:
javax.persistence.PersistenceException: Provider error. Provider: org.datanucleus.jpa.PersistenceProviderImpl
at javax.persistence.Persistence.createFactory(Persistence.java:176)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:112)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:66)
at com.my.jpa.EMF.<clinit>(EMF.java:8)
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
C 2012-10-24 12:21:46.893
Uncaught exception from servlet
java.lang.ExceptionInInitializerError
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
My code for persistance.xml is
<?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="JPATest">
<class>com.my.jpa.Contact</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.google.cloud.sql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms://instance_name/db" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>
My Entity Manager Factory Class is :
public final class EMF {
private static final EntityManagerFactory emfInstance = Persistence
.createEntityManagerFactory("JPATest");
private EMF() {
}
public static EntityManagerFactory get() {
return emfInstance;
}
}
Servlet is :
public class JPATestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
ContactService service = new ContactService();
service.createContact(new Contact("Manu", "Mohan", "686019", "TVM"));
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
Entity Class is :
#Entity
public class Contact {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String phoneNumber;
private String address;
public Contact() {
}
public Contact(String fn, String ln, String pn, String addr) {
this.firstName = fn;
this.lastName = ln;
this.phoneNumber = pn;
this.address = addr;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

One would think that if you want to use EclipseLink, then you would set the "provider" in "persistence.xml", since you have other JPA implementation(s) in the CLASSPATH too, or alternatively you fix the CLASSPATH to make sure there is only 1 JPA implementation present

Related

Java.lang.reflect.invocationTargetException in hibernate

Any one please solve my problem. I'm getting java.lang.reflect.invocationTargetException while I'm trying to save an object into oracle database(Oracle 10G).
Here is my model class named Student.java
package org.hibernatetest;
public class Student {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Here is my mapping file named Student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.hibernatetest.Student" table="STUDENT_2018">
<id name="id" column="STUDENT_ID"/>
<property name="name" column="STUDENT_NAME"></property>
<property name="email" column="STUDENT_EMAIL"></property>
</class>
</hibernate-mapping>
here is configuration file named as hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">Test</property>
<property name="hibernate.connection.password">Test</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="show_sql">true</property>
<mapping resource="resource/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
here is my persistent class named Test.java
package org.hibernatetest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
Student st = new Student();
st.setId(1);
st.setName("Mohan");
st.setEmail("mmohan668#gmail.com");
Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure("resource/hibernate.cfg.xml").buildSessionFactory();
Session s = sf.openSession();
s.save(st);
s.beginTransaction().commit();
s.evict(st);
}
}
Please help to resolve my problem . Thanks in advance.

HSQLDB Tables not generating

I have a database using HSQLDB, and my persistence.xml file is not creating the tables as I would expect. Here is my persistence.xml code:
<?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="DanPfeiffer-SE452-ProjectPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>java.user.jpa.User</class>
<class>java.score.jpa.Score</class>
<class>java.teeBox.jpa.TeeBox</class>
<class>java.course.jpa.Course</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:hsql://localhost/mydb"/>
<property name="javax.persistence.jdbc.user" value="SA"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create-tables"/>
<property name="eclipselink.deploy-on-startup" value="true" />
</properties>
</persistence-unit>
</persistence>
I have a few Java Beans written with #Entity annotation. Here's the simplest of those beans.
package main.java.user.jpa;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import main.java.score.IScore;
import main.java.score.jpa.Score;
import main.java.user.IUser;
#Entity
#NamedQuery(name = "findAllUsers", query = "select u from User u")
public class User implements Serializable, IUser {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int userId;
#NotNull
private String firstName;
#NotNull
private String lastName;
#NotNull
private double handicap;
#OneToMany
private Collection<Score> scores;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return this.firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return this.lastName;
}
public void setId(int id) {
this.userId = id;
}
public int getId() {
return userId;
}
public void setHandicap(double hcp) {
this.handicap = hcp;
}
public double getHandicap() {
return handicap;
}
#Override
public void setScores(Collection<Score> scores) {
if (this.scores != null){
for (Score temp : scores){
this.scores.add(temp);
}
}
else{
this.scores = scores;
}
}
#Override
public Collection<Score> getScores() {
// TODO Auto-generated method stub
return null;
}
public boolean equals(Object object){
boolean result = false;
if (object instanceof User){
User temp = (User)object;
if (temp.getFirstName().equals(this.firstName)
&& temp.getLastName().equals(this.lastName)
&& temp.getHandicap() == this.handicap){
result = true;
}
}
return result;
}
public String toString(){
String result = ("User: \nID: " + this.userId + "\nName:" + this.firstName + " " + this.lastName + " \nHandicap:" + this.handicap);
return result;
}
}
From my understanding, the persistence.xml file should drop and create all of the tables each time the hsqldb.jar file is run.
I haven't found an issue with my connection (it works when I connect, just no data), my persistence file or location. I originally populated the database this way.

Getting java.lang.NoSuchFieldError: ERRORS_IGNORED for hibernate-ogm with mongodb

I am trying to use hibernate-ogm with mongodb and getting no such fieds error
persistence.xml
<persistence-unit name="mongodb-test" transaction-type="JTA">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<properties>
<property name="hibernate.ogm.datastore.provider" value="mongodb"></property>
<property name="hibernate.ogm.datastore.host" value="192.168.0.237"></property>
<property name="hibernate.ogm.datastore.create_database" value="true"></property>
<property name="hibernate.ogm.datastore.database" value="anand_test"></property>
<property name="hibernate.ogm.mongodb.connection_timeout" value="5000"></property>
<property name="hibernate.ogm.mongodb.authentication_mechanism" value="PLAIN"></property>
<property name="hibernate.ogm.datastore.document.association_storage" value="IN_ENTITY"></property>
<property name="hibernate.ogm.mongodb.association_document_storage" value="GLOBAL_COLLECTION"></property>
<property name="hibernate.ogm.mongodb.write_concern" value="ACKNOWLEDGED"></property>
<property name="hibernate.ogm.mongodb.read_preference" value="PRIMARY_PREFERRED"></property>
</properties>
</persistence-unit>
Person.java
import javax.persistence.Entity;
import javax.persistence.Id;
import org.bson.types.ObjectId;
import org.hibernate.annotations.Type;
#Entity
public class Person {
#Id
#Type(type = "objectid")
private String id;
private String firstName;
private String lastName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Person(){
}
public Person(String firstName,String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
TestMongoconnection.java
import com.mongodb.Person;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class TestMongoConnection {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("mongodb-test");
EntityManager manager = entityManagerFactory.createEntityManager();
manager.getTransaction().begin();
Person anandMohan = new Person("Anand","Mohan");
manager.persist(anandMohan);
manager.getTransaction().commit();
manager.close();
}
}
I am having mongodb version 3.0.2 and hibernate-ogm 4.2.0 final with mongodb java version 3.x jars
The problem is with the java jar version of the mongodb as 3.x version is not yet supported have to use 2.x version of it
https://forum.hibernate.org/viewtopic.php?f=31&t=1040127&p=2485319#p2485319

Unable to inject Mongo Repository into my test class

Getting below exception when trying to inject Mongo repository into test
class.org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.sg.tutswheel.test.repositories.CustomerRepository': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.sg.tutswheel.test.repositories.CustomerRepository com.sg.tutswheel.test.repositories.CustomerRepository.customerRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sg.tutswheel.test.repositories.CustomerRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) ~[spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:252) [spring-test-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.11.jar:na]"
Junit
#ContextConfiguration(locations{"classpath:application/springcontexts/appContext-persistence.xml"})
public class CustomerRepository extends AbstractTestUnit{
#Autowired
CustomerRepository customerRepository;
#Test
public void testContextLoader() {
//....
}
}
appContext-persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<mongo:mongo id="mongo" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg value="databaseName" />
</bean>
<mongo:repositories base-package="com.sg.tutswheel.persistence.repositories" mongo-template-ref="mongoTemplate" />
</beans>
CustomerRepository
public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long>{
Customer findByFirstName(String firstName);
}
Customer.java
#Document
public class Customer extends AbstractEntity{
private String firstName, lastName;
public Customer(String firstName, String lastName) {
Assert.hasText(firstName,"First Name cannot be null or empty");
Assert.hasText(lastName, "Last Name cannot be null or empty");
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Thanks in advance.
I think the problem is that your test class name is CustomerRepository - the same as you real CustomerRepository which you are testing.
Therefore Spring is trying to find a bean of your test class type (not the repository type) and cannot find it.
Try to rename test class to something different. For example:
#ContextConfiguration(locations{"classpath:application/springcontexts/appContext-persistence.xml"})
public class CustomerRepositoryTest extends AbstractTestUnit{
#Autowired
CustomerRepository customerRepository;
#Test
public void testContextLoader() {
//....
}
}

Java EE 7 / EJB / JPA - Entity Manager not creating transaction when persisting entity

I have a client app:
public static void main(String[] args) throws NamingException {
Properties p = new Properties();
p.put(Context.PROVIDER_URL, "t3://127.0.0.1:7001");
p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
InitialContext ctx = new InitialContext(p);
ServiceEJBStatelessRemote service = (ServiceEJBStatelessRemote)ctx.lookup("ServiceEJBStatelessJNDI#com.marcos.service.remote.ServiceEJBStatelessRemote");
User user = new User(123, "Foo BAR", "ertddeew45", "foousername");
Long id = service.insertUser(user);
System.out.println("User has been created with id: "+id);
Whenever I try to persist this entity in the DB, I get no exception but isn't getting stored in my DB.
In my service (stateless EJB), I have two methods, one for insert and another for retrieve; the retrieving method works just fine, so then I can see that the Entity Manager attribute works, and my persistance unit as well as I can go to the DB and retrieve the value Im looking for.
But when I invoke the insertUser() method, I get no error but the entity is not saved it in the DB, it is like if there were no commit action at all.
Im deploying my app in a Weblogic 12c server
In order to run my client app, Im adding wlthint3client.jar into my buildpath
In my insertUser() method I cant make any call to getTransaction() cos then I get an exeception.
Am I missing something?
This is my service class:
#Stateless(mappedName = "ServiceEJBStatelessJNDI", name="ServiceEJBStateless")
#TransactionManagement(TransactionManagementType.CONTAINER)
public class ServiceEJBStateless implements ServiceEJBStatelessRemote {
#PersistenceContext(unitName="Test2Jpa2")
EntityManager em;
public ServiceEJBStateless() {
}
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public long insertUser(User user) {
em.persist(user);
em.merge(user);
return user.getUserId();
}
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public User findUser(long id) {
return em.find(User.class, id);
}
This is my persistance.xml
<persistence-unit name="Test2Jpa2" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.marcos.domain.User</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#127.0.0.1:1521:xe"/>
<property name="javax.persistence.jdbc.user" value="hibernatetest"/>
<property name="javax.persistence.jdbc.password" value="pwd123"/>
</properties>
</persistence-unit>
And this is my entity:
#Entity
#Table(name="USERS")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="USER_ID")
private long userId;
private String fullname;
private String password;
private String username;
public User() {
}
public User(String fm, String pwd, String username) {
this.fullname = fm;
this.password = pwd;
this.username = username;
}
public User(long id, String fm, String pwd, String username) {
this.userId = id;
this.fullname = fm;
this.password = pwd;
this.username = username;
}
public long getUserId() {
return this.userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getFullname() {
return this.fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString(){
return "Id: "+this.userId+"\n"+
"Name: "+this.fullname+"\n"+
"Username: "+this.username+"\n"+
"Password: "+this.password;
}