How to validate model with eclipselink jpa - java

I hava a model, and i need to validate model with eclipselink jpa
and i add anotation #NotEmpty validate name if empty, but when i save/persist model, validate not work
#Entity
public class Role {
#Id
private String id;
#NotEmpty
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
my jpa configuration xml like this
<?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="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>app.test.Model.Role</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>

The JPA API (which EclipseLink implements) is nothing to do with the Bean Validation API.
To utilise the Bean Validation API you need the Bean Validation API jar (javax.validation), together with an implementation of that API (Apache BVAL, Hibernate Validator, etc) in your CLASSPATH.
The only thing JPA provides is to auto-enable validation as per this link, but the default is "auto" so nothing required really for that

Related

I receive exception No Persistence provider for EntityManager in IntelliJ

Someone to knows where can be the problem -
Could not find any META-INF/persistence.xml file in the classpath
I use IntelliJ and h2 database connection with Hibernate
There are my classes:
persistence:
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress DeprecatedClassUsageInspection -->
<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="StudentPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>model.StudentInfo</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:~/JPA_App" />
<property name="hibernate.connection.user" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
</properties>
</persistence-unit>
</persistence>
Entity class:
package model;
import javax.persistence.*;
#Entity
#Table(name = "Student")
public class StudentInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name", length = 30, nullable = false)
private String name;
#Column(name = "lastname", length = 30, nullable = false)
private String lastname;
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 getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
and Main class
package model;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class AddStudent {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
StudentInfo student = new StudentInfo();
student.setId(0);
student.setName("John");
student.setLastname("Doe");
em.persist(student);
em.getTransaction().commit();
em.close();
emf.close();
}
}
In eclipse this simple source works but in IntelliJ I received this exception.
I would be grateful for any ideas to resolve this error.
Best regards,
D. Balamjiev
Just move your META-INF folder at the root of one of build paths of your IDE.
For example, move META-INF folder to the web folder and it should be available at the runtime.
By using a build tool such as Maven or Gradle, you would not have these kinds of problem any longer since the layout is standard and therefore the same whatever the IDE you are using.
For example, in your case, it would be both for Eclipse and IntelliJ : src/main/resources/META-INF

JPA Eclipselink Multitenant, table doesn't exist error

i'm trying to make a simple multitenant example to run, using Eclipselink 2.5.2, and MySQL.
When trying to persist an entity asigned to a tenant id, mysql server throws an error: "Table 'jpatest.tenant1_userdata' doesn't exist". (userdata being the entity, jpatest the database name, and tenant1 the tenant-id)
The table indeed doesn't exist, the database jpatest do exist. I was expecting eclipselink to autogenerate the tables each time i try to persist with a new tenant id.
So the question would be:
How can i force Eclipselink to create the tables?
If that is not possible; How can i create tables at runtime?
Here's the code:
Entity:
#Entity
#Table(name = "userdata")
#Multitenant(value = MultitenantType.TABLE_PER_TENANT)
#TenantTableDiscriminator(type = TenantTableDiscriminatorType.PREFIX, contextProperty = "tenant-id")
public class UserData implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private static final long serialVersionUID = 1L;
private String name;
.
.
.
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="MultiTeanantTest" transaction-type="RESOURCE_LOCAL">
<class>UserData</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpatest" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-database-schemas" value="true"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
Main class:
public class Main {
public static void main(String[] args) {
UserData ud = new UserData();
ud.setNombre("John);
Map properties = new HashMap<>();
properties.put("tenant-id", "tenant1");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("MultiTeanantTest", properties );
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(ud);
em.getTransaction().commit();
}
}
Hope someone can give me a tip in what i'm doing wrong.
DDL generation will not be supported in a Multitenant Scenario by Eclipselink.
Refer to this link for more information, https://wiki.eclipse.org/EclipseLink/DesignDocs/Multi-Tenancy/TablePerTenant

Hibernate 4.3.6 and Glassfish 4.0 JPA 2.1 object is not an instance of declaring class

I'm using Hibernate 4.3.6 and Glassfish 4.0 for my ejb project.
My test Dao class :
#PersistenceContext
private EntityManager entityManager;
public void saveTest(){
Foo testFoo = new Foo();
testFoo.setSomething("test");
entityManager.persist(testFoo);
entityManager.flush();
}
and POJO class Foo.class:
#Entity
#Table(name = "FOO")
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String something;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "T_ID", unique = true, nullable = false, precision = 15, scale = 0)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "T_SOMETHING", length = 50)
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.adi = something;
}
}
persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.1">
<persistence-unit name="TestAppUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/TestApp</jta-data-source>
<class>com.example.test.Foo</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
I can list table data, get data with query and i can remove data from table. But i can't persist or merge.
Exception is:
IllegalArgumentException occurred calling getter of com.example.test.Foo.id
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:192)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:346)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4746)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4465)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:243)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:511)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:671)
....
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:169)
Where am I doing wrong?
This project working on Glassfish 3.1 with persistence.xml version 1.0(jpa) and without this line :
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
Thanks in advance
I found it. Maybe others they encounter this problem. I wanted to share the solution.
The problem caused from Hibernate and "#PersistenceContext" annotation.
I change to Hibernate version to 4.3.5 and problem solved. Hibernate 4.3.6 and 4.3.7 has same problem. It's caused by different classloaders. Ejb Classloader and web app Classloader is different.

org.apache.openjpa.persistence.ArgumentException while running the main class

I using using maven simple java project
Im getting the following exception while running the main class
346 INFO [main] openjpa.Runtime - OpenJPA dynamically loaded the class
enhancer. Any classes that were not enhanced at build time
will be enhanced when they are loaded by the JVM.
414 INFO [main] openjpa.Runtime - Starting OpenJPA 2.3.0
<openjpa-2.3.0-r422266:1540826 fatal user error>
org.apache.openjpa.persistence.ArgumentException: The persistence provider is
attempting to use properties in the persistence.xml file to resolve the data
source. A Java Database Connectivity (JDBC) driver or data source class name
must be specified in the openjpa.ConnectionDriverName or
javax.persistence.jdbc.driver property. The following properties are available
in the configuration: "org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl#442ce698".
at org.apache.openjpa.jdbc.schema.DataSourceFactory.newDataSource(DataSourceFactory.java:72)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.createConnectionFactory(JDBCConfigurationImpl.java:849)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:602)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1518)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:535)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:460)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:121)
at org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:967)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:958)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:643)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:203)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:155)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:226)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:153)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:59)
at org.msharma.JpaImpl.main(JpaImpl.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
My entity clas
#Entity(name ="customer")
public class Customer implements Serializable{
#Id
#Column(name ="cust_id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long custId;
#Column(name = "first_name",length = 50, nullable = false)
private String firstName;
#Column(name = "last_name",length = 50)
private String lastName;
// By default column name is same as attribute name
private String street;
private String appt;
private String city;
#Column(name = "zip_code",length = 50, nullable = false)
private String zipCode;
#Column(name = "cust_type",length = 50, nullable = false)
private String custType;
#Version
#Column(name = "last_updated_time")
private Date updatedTime;
public Customer(){}
// getters and setters
}
This is my persistence.xml
<?xml version="1.0"?>
<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="testjpa" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>org.somepack.Customer</class>
<properties>
<property name="openjpa.ConnectionURL"
value="jdbc:mysql://localhost:3306/test"/>
<property name="openjpa.ConnectionDriverName"
value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionUserName" value="root"/>
<property name="openjpa.ConnectionPassword" value="pass"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
</properties>
</persistence-unit>
</persistence>
This is my mainClass
public static void main(String[] args) {
try {
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("testjpa");
EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Customer customer = new Customer();
//set the properties to the customer object
entityManager.persist(customer);
entityTransaction.commit();
entityManager.close();
entityManagerFactory.close();
}
catch (Exception e){
e.printStackTrace();
}
}
How do I resolve the problem .
I have openjpa, openjpa-persistence-jdbc, mysql-connector-java dependencies in my POM.xml
and my persistence.xml is under src/main/resources
As you said your persistence.xml is under src/main/resources so may be it is unable to read it
you must place it under src/main/resources/META-INF
One more thing add
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
to your persistence.xml.
If you add the openjpa.jdbc.SynchronizeMappings property as shown below OpenJPA will auto-create all your tables, all your primary keys and all foreign keys exactly to match your objects
Add <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> to your persistence.xml:
<?xml version="1.0"?>
<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="testjpa" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>org.somepack.Customer</class>
<properties>
<property name="openjpa.ConnectionURL"
value="jdbc:mysql://localhost:3306/test"/>
<property name="openjpa.ConnectionDriverName"
value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionUserName" value="root"/>
<property name="openjpa.ConnectionPassword" value="pass"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</properties>
</persistence-unit>
</persistence>

NullPointerException using datanucleus-json with S3

I'm using datanucleus 3.2.7 from Maven, trying to use the Amazon S3 JPA provider. I can successfully write data into S3, but querying either by using "SELECT u FROM User u" or "SELECT u FROM User u WHERE id = :id" causes a NullPointerException to be thrown when I call query.getResultList().
Using the RDBMS provider, everything works perfectly. Is there something I'm doing wrong?
Main.java
EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyUnit");
EntityManager entityManager = factory.createEntityManager();
Query query = entityManager.createQuery("SELECT u FROM User u", User.class);
List<User> users = query.getResultList(); // Null pointer exception here (This is line 16!)
for(User u:users)
System.out.println(u);
User.java
package test;
import javax.persistence.*;
#Entity
#Table(name = "User")
public class User {
#Id
public String id;
public String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id+" : "+name;
}
}
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_1_0.xsd"
version="1.0">
<persistence-unit name="MyUnit">
<class>test.User</class>
<exclude-unlisted-classes />
<properties>
<properties>
<property name="datanucleus.ConnectionURL" value="amazons3:http://s3.amazonaws.com/" />
<property name="datanucleus.ConnectionUserName" value="xxxxx" />
<property name="datanucleus.ConnectionPassword" value="xxxxx" />
<property name="datanucleus.cloud.storage.bucket" value="my-bucket" />
</properties>
<property name="datanucleus.autoCreateSchema" value="true" />
</properties>
</persistence-unit>
</persistence>
Exception
java.lang.NullPointerException
at org.datanucleus.NucleusContext.isClassWithIdentityCacheable(NucleusContext.java:1840)
at org.datanucleus.ExecutionContextImpl.getObjectFromLevel2Cache(ExecutionContextImpl.java:5287)
at org.datanucleus.ExecutionContextImpl.getObjectFromCache(ExecutionContextImpl.java:5191)
at org.datanucleus.ExecutionContextImpl.findObject(ExecutionContextImpl.java:3137)
at org.datanucleus.store.json.CloudStoragePersistenceHandler.getObjectsOfCandidateType(CloudStoragePersistenceHandler.java:367)
at org.datanucleus.store.json.query.JPQLQuery.performExecute(JPQLQuery.java:94)
at org.datanucleus.store.query.Query.executeQuery(Query.java:1786)
at org.datanucleus.store.query.Query.executeWithMap(Query.java:1690)
at org.datanucleus.api.jpa.JPAQuery.getResultList(JPAQuery.java:194)
at test.Main.main(Main.java:16)
This error appears to be happening as datanucleus deserializes the JSON for an entry. Deleting everything from the bucket returns the empty set without incident. By turning off L2 Caching, I made the exception occur somewhere else. It seems that ExecutionContextImpl.findObject is being given a null id.
datanucleus-json version 3.2.1 likely fixes that, but that's for you to confirm

Categories

Resources