I'm tring to insert my student object to Students table in mydb database, but always get exception. However connecting to table using Connection works properly. I'm using Eclipse with EclipseLink.
entity class
package student;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "STUDENTS")
public class Student {
#Id
#Column(name = "studentID")
#GeneratedValue
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "GROUPNUM")
private String groupNum;
#Column(name="AVGMARK")
private double avgMark;
public Student(){}
public Student(String name, String groupNum, double avgMark) {
this.name = name;
this.groupNum = groupNum;
this.avgMark = avgMark;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroupNum() {
return groupNum;
}
public void setGroupNum(String groupNum) {
this.groupNum = groupNum;
}
public double getAvgMark() {
return avgMark;
}
public void setAvgMark(double avgMark) {
this.avgMark = avgMark;
}
}
method in my class
package connector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public void insertIntoStudents(Student st) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory(
"students");
EntityManager em = factory.createEntityManager();
// Begin a new local transaction so that we can persist a new entity
em.getTransaction().begin();
em.persist(st);
em.getTransaction().commit();
em.close();
}
persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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="students" transaction-type="RESOURCE_LOCAL">
<class>student.Student</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost/mydb" />
<property name="javax.persistence.jdbc.user" value="sqluser" />
<property name="javax.persistence.jdbc.password" value="sqluserpw" />
</property></properties>
</persistence-unit>
</persistence>
Exception
Exception in thread "main" java.lang.IllegalArgumentException: Object: student.Student#62d7ef8f is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4228)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at connector.DBconnector.insertIntoStudents(DBconnector.java:60)
at Main.main(Main.java:10)
Put full name of entity in persistence xml. I mean full package name
package com.mycom.api.data;
#entity
public class student{
...
..
..
}
You should put com.mycom.api.data.student in persistence.xml.
Related
i wanna create objects with intellij (jpa) system,
but after i create objects,
there's no change in h2 console.
i expect that the objects are made like this, enter image description here
(wanna make ITEM and MOVIE objects)
but what i got is this. enter image description here
these are the codes that i wrote.
package hellojpa;
import javax.persistence.Entity;
#Entity
public class Album extends Item{
private String artist;
}
package hellojpa;
import javax.persistence.Entity;
#Entity
public class Book extends Item{
private String author;
private String isbn;
}
package hellojpa;
import org.hibernate.engine.internal.JoinSequence;
import org.hibernate.mapping.Join;
import javax.persistence.*;
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Item {
#Id
#GeneratedValue
private Long id;
private String name;
private int price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package hellojpa;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaMain {
public static void main(String[] args){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try{
Movie movie = new Movie();
movie.setDirector("aaaa");
movie.setActor("bbbb");
movie.setName("바람과 함께 사라지다");
movie.setPrice(10000);
tx.commit();
}catch(Exception e){
tx.rollback();
} finally{
em.close();
}
emf.close();
}
}
package hellojpa;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
#Entity
public class Locker {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToOne(mappedBy = "locker")
private Member member;
}
package hellojpa;
import net.bytebuddy.dynamic.TypeResolutionStrategy;
import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Member {
#Id #GeneratedValue
#Column(name = "MEMBER_ID")
private Long id;
#Column(name = "USERNAME")
private String username;
#ManyToOne
#JoinColumn(name = "Team_ID",insertable = false, updatable = false)
private Team team;
#OneToOne
#JoinColumn(name ="LOCKER_ID")
private Locker locker;
#OneToMany(mappedBy = "member")
private List<MemberProduct> memberProducts = new ArrayList<>();
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
}
package hellojpa;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
public class MemberProduct {
#Id
#GeneratedValue
private Long id;
#ManyToOne
#JoinColumn(name="MEMBER_ID")
private Member member;
#ManyToOne
#JoinColumn(name = "PRODUCT_ID")
private Product product;
private int count;
private int price;
private LocalDateTime orderDateTime;
}
package hellojpa;
import javax.persistence.Entity;
#Entity
public class Movie extends Item{
private String director;
private String actor;
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
}
package hellojpa;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Product {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany (mappedBy = "product")
private List<MemberProduct> memberProducts = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package hellojpa;
public enum RoleType {
GUEST, USER, ADMIN
}
package hellojpa;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Team {
#Id #GeneratedValue
#Column(name = "TEAM_ID")
private Long id;
private String name;
#OneToMany
#JoinColumn(name = "TEAM_ID")
private List<Member> members = new ArrayList<>();
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public List<Member> getMembers() {
return members;
}
public void setMembers(List<Member> members) {
this.members = members;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="hello">
<properties>
<!-- 필수 속성 -->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!-- 옵션 -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="10"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
You forgot to use the entityManager to persist your new entity. Therefore, jpa does not know about the new entity and nothing is saved.
Just add : em.persist(movie);
The screenshots you provided, in combination with <property name="hibernate.hbm2ddl.auto" value="create" />, suggests that you were not finished creating entity classes when you first run your application. Now if you use hibernate.hbm2ddl.auto = create and there is allready a schema present in your H2, it won't update the schema even though you added one or more entity classes.
The community documentation suggests that you use hibernate.hbm2ddl.auto = update in order to update the schema when the application is run.
Please note that, according to this post, it is not safe to use update in a productive environment.
Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates in production. Write your own patches, review them with DBA, test them, then apply them manually.
Theoretically, if hbm2ddl update worked in development, it should work in production too. But in reality, it's not always the case.
I hope this helps.
I have the following error:
"class can not be selected as the root of criteria query because it is not an entity."
I have annotated the class with #Entity, #Table and registered the entity in the persistence.xml.
I'm getting the error when I'm creating a Root object from my Entity class:
Root<ConfigurazioniEntity> root = cq.from(ConfigurazioniEntity.class);
Entity class:
package it.convalida.nazionale.core.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = ConfigurazioniEntity.TABLE_NAME)
public class ConfigurazioniEntity implements BaseEntity {
private static final long serialVersionUID = 6651666466423423207L;
public static final String TABLE_NAME = "PRA_CONFIG_DL98";
#Id
#Column(name = "ID_PRA_CONFIG", nullable = false, updatable = false)
private Long idPraConfig;
#Column(name = "NOME_PARAM")
private String nomeParam;
#Column(name = "VALORE_PARAM")
private String valoreParam;
/**
* 1 = ATTIVO, 0 = NON ATTIVO
*/
#Column(name = "ATTIVO")
private String attivo;
public Long getIdPraConfig() {
return idPraConfig;
}
public void setIdPraConfig(Long idPraConfig) {
this.idPraConfig = idPraConfig;
}
public String getNomeParam() {
return nomeParam;
}
public void setNomeParam(String nomeParam) {
this.nomeParam = nomeParam;
}
public String getValoreParam() {
return valoreParam;
}
public void setValoreParam(String valoreParam) {
this.valoreParam = valoreParam;
}
public String getAttivo() {
return attivo;
}
public void setAttivo(String attivo) {
this.attivo = attivo;
}
}
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="convalidaNazionalePersistentUnit" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>jdbc/convalidaNazionale</jta-data-source>
<class>it.convalida.nazionale.core.entity.AssociaPratica</class>
<class>it.convalida.nazionale.core.entity.Fascicolo</class>
<class>it.convalida.nazionale.core.entity.Note</class>
<class>it.convalida.nazionale.core.entity.LogAssociaPratica</class>
<class>it.convalida.nazionale.core.entity.ConfigurazioniEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.sharedCache.mode" value="NONE" />
<property name="openjpa.DataCache" value="false" />
<property name="openjpa.QueryCache" value="false" />
<property name="openjpa.Log" value="DefaultLevel=INFO,Tool=INFO" />
<property name="openjpa.jdbc.DBDictionary" value="DisableAlterSeqenceIncrementBy=true" />
<property name="openjpa.jdbc.MappingDefaults"
value="ForeignKeyDeleteAction=restrict,JoinForeignKeyDeleteAction=restrict" />
</properties>
</persistence-unit>
</persistence>
Dao:
package it.convalida.nazionale.core.dao.impl;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.convalida.nazionale.core.dao.ConfigurazioniDao;
import it.convalida.nazionale.core.eccezioni.ConvalidaNazionaleCoreException;
import it.convalida.nazionale.core.entity.ConfigurazioniEntity;
public class ConfigurazioniDaoImpl extends GenericDaoImpl<ConfigurazioniEntity> implements ConfigurazioniDao {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurazioniDaoImpl.class);
public ConfigurazioniDaoImpl() {
super(ConfigurazioniEntity.class);
}
/**
* #param startFrom
* #param pageSize
* #return
* #throws ConvalidaNazionaleCoreException
*/
public List<ConfigurazioniEntity> findConfigurazioni(int startFrom, int pageSize)
throws ConvalidaNazionaleCoreException {
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ConfigurazioniEntity> cq = cb.createQuery(ConfigurazioniEntity.class);
Root<ConfigurazioniEntity> root = cq.from(ConfigurazioniEntity.class);
cq.select(root);
TypedQuery<ConfigurazioniEntity> query = em.createQuery(cq).setFirstResult(startFrom).setMaxResults(pageSize);
return getResultList(query);
} catch (Exception e) {
LOGGER.error("Errore nel findConfigurazioni", e);
throw new ConvalidaNazionaleCoreException(e);
}
}
}
All other entities are done in the same way and are recognized as entities, but not mine.
I have the error only on my Entity.
For some reason it didn't recognize the Entity.
After launching "Maven clean install" all worked properly
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.
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
Using Play! Framework 2.0.2, when I add several items from my java project to my H2 test database I only see one single item in the ITEM table. The single item being the last entry that i've persisted. I thought that this my be due the db being recreated at every commit. I therefor thought of adding the JPA.ddl=update property in my application.conf file. But this simply breaks with the following error. What
Here is my code (in the Item.save() method):
package models;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Persistence;
#Entity
public class Item {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public String name;
public String dev;
public String type;
public int quantity;
public BigDecimal unitPrice;
public Item() {}
public Item(String name, String dev, String type, int quantity,
BigDecimal unitPrice) {
super();
this.name = name;
this.dev = dev;
this.type = type;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
/**
* Insert this new computer.
*/
public void save() {
//this.id = id;
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(this);
entityManager.getTransaction().commit();
entityManager.close();
}
}
Here is the error message
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named update
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69) ~[hibernate-jpa-2.0-api-1.0.1.Final.jar:1.0.1.
Final]
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47) ~[hibernate-jpa-2.0-api-1.0.1.Final.jar:1.0.1.
Final]
at play.db.jpa.JPAPlugin.onStart(JPAPlugin.java:35) ~[play_2.9.1.jar:2.0.2]
at play.api.Play$$anonfun$start$1.apply(Play.scala:60) ~[play_2.9.1.jar:2.0.2]
at play.api.Play$$anonfun$start$1.apply(Play.scala:60) ~[play_2.9.1.jar:2.0.2]
at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:59) ~[scala-library.jar:0.11.3]
I believe you're going to need a persistence.xml file to be contained within your /conf/META-INF/ directory, and from there need to define a persistence unit. I believe this is because you're using Hibernate correct?
An example of what yours can look like
<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="update">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.url" value="jdbc:h2:mem:events"/>
</properties>
</persistence-unit>
</persistence>
In your tag you'll also need to include any <jar-file> or <class> you are to be using as well.