Entity Class is a non Entity? - java

I got the following Error:
[class model.VerkaufterArtikel] uses a non-entity [class model.Verkauf] as target entity in the relationship attribute [field verkauf].
But the class is listed in the persistence.xml. And I tried also to not exlude unlisted classes.
I'm using EclipseLink as JPA Implementation.
I tried to exlude the relation but then I was not able to persist Verkauf. The other classes are working correctly.
The situation is: I have a sale(Verkauf) wich contains sold items(VerkaufteArtikel).
model.Verkauf:
package model;
#Entity
#Table(name = "verkauf")
#NamedQuery(name = "Verkauf.findAll", query = "SELECT v FROM Verkauf v")
public class Verkauf implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int verkID;
private int gegeben;
#OneToMany(mappedBy="verkauf")
private List<VerkaufterArtikel> verkaufArtikels = new ArrayList<VerkaufterArtikel>();
model.VerkaufterArtikel:
#Entity
#Table(name="verkauf_artikel")
#NamedQuery(name="VerkaufArtikel.findAll", query="SELECT v FROM VerkaufterArtikel v")
public class VerkaufterArtikel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private float anz;
private int artID;
private int preispro;
#ManyToOne
#JoinColumn(name="verkaufID")
private Verkauf verkauf;
My 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="dbm" transaction-type="RESOURCE_LOCAL">
<!-- <exclude-unlisted-classes>false</exclude-unlisted-classes>-->
<class>model.Artikel</class>
<class>model.ArtikelInWarenkorb</class>
<class>model.VerkaufterArtikel</class>
<class>model.Verkaeufer</class>
<class>model.Verkauf</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mdb" />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="eclipselink.allow-zero-id" value="true" />
</properties>
</persistence-unit>
</persistence>
And the Tables:
CREATE TABLE `verkauf_artikel` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`verkaufID` INT(11) NULL DEFAULT NULL,
`artID` INT(11) NULL DEFAULT NULL,
`anz` FLOAT NULL DEFAULT NULL,
`preispro` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
CREATE TABLE `verkauf` (
id` INT(11) NOT NULL AUTO_INCREMENT,
`verkID` INT(11) NULL DEFAULT '0',
`zeit` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`gegeben` INT(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
Thank you!

I think your #ManyToOneMapping is not correct, it should look like this:
#ManyToOne
#JoinColumn(name="verkID")
private Verkauf verkauf;

I finally found the reason for this error.
I had a getSum() method at the bottom of the class. I removed the method and everything is working fine now!
public int getSum() {
return (int) getVerkaufArtikels()
.stream()
.mapToDouble(acc -> ((double) acc.getPreispro() * acc.getAnz()))
.sum();
}

Related

Problems with java #GeneratedValue (strategy = GenerationType.IDENTITY) using MariaDB 10.4 and eclipselink

I am developing a REST web service in Java EE I am using: Glassfish 5.0 (build 25), MariaDB 10.4 and eclipselink (JPA 2.1)
here is my code:
commande_line table
CREATE TABLE IF NOT EXISTS `cooldb`.`commande_line` (
`id` INT NOT NULL AUTO_INCREMENT,
`quantity` INT NULL,
`discount` INT NULL,
`dish` INT NOT NULL,
`commande` INT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC),
INDEX `fk_commande_line_dish1_idx` (`dish` ASC),
INDEX `fk_commande_line_commande1_idx` (`commande` ASC),
CONSTRAINT `fk_commande_line_dish1`
FOREIGN KEY (`dish`)
REFERENCES `cooldb`.`dish` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_commande_line_commande1`
FOREIGN KEY (`commande`)
REFERENCES `cooldb`.`commande` (`id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://java.sun.com/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">
<!-- Define Persistence Unit -->
<persistence-unit name="my_persistence_unit" transaction-type="JTA">
<jta-data-source>jdbc/mariadb</jta-data-source>
<class>com.yac.model.Address</class>
<class>com.yac.model.Commande</class>
<class>com.yac.model.CommandeLine</class>
<class>com.yac.model.Dish</class>
<class>com.yac.model.Dishtype</class>
<class>com.yac.model.Ingredient</class>
<class>com.yac.model.Payement</class>
<class>com.yac.model.Profil</class>
<class>com.yac.model.Restaurant</class>
<class>com.yac.model.Userapp</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
</persistence>
commandeline entity
public class CommandeLine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "quantity")
private Integer quantity;
#Column(name = "discount")
private Integer discount;
#JoinColumn(name = "commande", referencedColumnName = "id")
#ManyToOne(optional = false)
private Commande commande;
#JoinColumn(name = "dish", referencedColumnName = "id")
#ManyToOne(optional = false)
private Dish dish;
//Constructor
// Setter and Getter
}
commandeline web service
#Stateless
#Path("commandeline")
public class CommandeLineFacadeREST extends AbstractFacade<CommandeLine> {
#PersistenceContext(unitName = "my_persistence_unit")
private EntityManager em;
public CommandeLineFacadeREST() {
super(CommandeLine.class);
}
#POST
#Override
#Consumes(MediaType.APPLICATION_JSON)
public void create(CommandeLine entity) {
super.create(entity);
}
#Override
protected EntityManager getEntityManager() {
return em;
}
}
AbstractFacade
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
}
The problem is when I test my web service with Postman and I try to insert a record with a POST request
here is what I receive as error message:
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: (conn=158) Table 'cooldb.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQ_GEN_SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?") ...
I don't understand why the problem with SEQUANCE when I use #GeneratedValue (strategy = GenerationType.IDENTITY).
When I change with #GeneratedValue (strategy = GenerationType.SEQUENCE) and I create the table with the following script:
CREATE SEQUENCE SEQUANCE START WITH 1 INCREMENT BY 1;
by applying the solution shown in : Table 'customerjpa.sequence' doesn't exist JPA
but the same probleme
thank you in advance for your help.
The problem is solved using Chris comments, i just add the following line in my persistence.xml file:
<property name="eclipselink.target-database" value="MySQL"/>
Thank you very much Chris.
So my new persistence.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://java.sun.com/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">
<!-- Define Persistence Unit -->
<persistence-unit name="my_persistence_unit" transaction-type="JTA">
<jta-data-source>jdbc/mariadb</jta-data-source>
<class>com.yac.model.Address</class>
<class>com.yac.model.Commande</class>
<class>com.yac.model.CommandeLine</class>
<class>com.yac.model.Dish</class>
<class>com.yac.model.Dishtype</class>
<class>com.yac.model.Ingredient</class>
<class>com.yac.model.Payement</class>
<class>com.yac.model.Profil</class>
<class>com.yac.model.Restaurant</class>
<class>com.yac.model.Userapp</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-database" value="MySQL"/>
</properties>
</persistence-unit>
</persistence>
I just specified the database platform in MySQL in the persistence.xml file of the moment MariaDB is based on it, because MariaDB is not mentioned in the list.
If there are other suggestions do not hesitate thank you.
Another Solution:
Add ?useMysqlMetadata=true to your JDBC URL connection as bellow:
<property name="URL" value="jdbc:mariadb://[HOST]:[PORT]/[DB NAME]?useMysqlMetadata=true"/>
that will make MariaDB use MySQL meta data and then eclipselink will detect it as MySQL.

One to one relationship select query fetches data once first time only

I'm trying to apply one to one relationship between two entities
first entity:
Video and OrganzationVideo every OrganizationVideo has one video entity
So I did the following
first organization_video table
CREATE TABLE `organization_video` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
video table
CREATE TABLE `video` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(100) DEFAULT NULL,
// rest of table contents
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
then I added constraint in organization_video table
CONSTRAINT `FK_organization_video` FOREIGN KEY (`id`) REFERENCES `video` (`id`)
Then generated entities
Video.java
#Entity
#Table(name = "video")
public class Video extends Persistable<Long> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Long id;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "video")
private OrganizationVideo organizationVideo;
\\ rest of video contetns
}
OrganizationVideo.java
#Entity
#Table(name = "organization_video")
public class OrganizationVideo extends Persistable<Long> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Long id;
#JoinColumn(name = "id", referencedColumnName = "id")
#OneToOne(optional = false)
private Video video;
\\ rest of organziation video contents
}
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://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Default_Persistence_Unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>jdbc/defaultDataSource</non-jta-data-source>
<properties>
<property name="hibernate.transaction.auto_close_session" value="false"/>
<property name="hibernate.max_fetch_depth" value="0"/>
<property name="hibernate.connection.release_mode" value="auto"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.cglib.use_reflection_optimizer" value="true"/>
</properties>
</persistence-unit>
</persistence>
everything worked perfectly when persisting objects
the issue is with the fetching query
StringBuilder queryStr = new StringBuilder("select v from Video v where v.organizationVideo is null");
Query query = getEntityManager().createQuery(queryStr.toString());
return query.getResultList();
The weird behavior is that this query fetches data once then doesn't fetch any data tried to use #PrimaryKeyJoinColumn and changed id generation type with no luck but indeed there is something wrong it's strange to see data once first time when I tried to remove is null from query it fetches data but with null value assigned to OrganizationVideo then why the query doesn't work except at first time.
You will have to check the SQL that is generated for the query, but I'm guessing that since the ID is the foreign key and it is autogenerated, inserting entities causes problems with your query. Try fixing your model first:
Either the OrganizationVideo ID needs to be set by the video relationship (if using JPA 2.0):
#Entity
#Table(name = "organization_video")
public class OrganizationVideo extends Persistable<Long> {
#Id
#JoinColumn(name = "id", referencedColumnName = "id")
#OneToOne(optional = false)
private Video video;
\\ rest of organziation video contents
}
That, or you make one of the ID mappings within OrganizationVideo insertable=false, updatable=false. if you do this, then you must set the other fields with in OrganizationVideo within the application yourself, and only after the Video instance has an ID value assigned. Since you are using identity, this means you would have to persist the vidoe, flush, and then use that value within the OrganizationVideo before it can be persisted.
It would be easier for your model if you could just add a foreign key to the OrganizationVideo table and use that to reference the Video ID.

What causes "java.lang.IllegalArgumentException: Can not set java.lang.Integer field"

I cannot resolve these new exceptions
Can not set java.lang.Integer field GcmRegistraionIdentity.gcmId to GcmRegistraionIdentity
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of GcmRegistraionIdentity.gcmId
My Dynamic Web Project (Jee7) targeted to
GlassFish Server Open Source Edition 4.1 (build 13)
Hibernate
Hibernate Core {4.3.7.Final}
My Persistence.xml
<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://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="testPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/testDB</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Heres my EDITED entity class (partial: e.g Getters/Setters NOT SHOWN)
#Entity
#Table(name = "gcm_registration")
public class GcmRegistraionIdentity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "gcm_id", unique = true, nullable = false, insertable = false, updatable = false)
private Integer gcmId;
#Column(name = "registration_id")
private String registraionId = null;
#Column(name = "created")
#Temporal(TemporalType.TIMESTAMP)
private Date created;
public Integer getGcmId() {
return gcmId;
}
public void setGcmId(final Integer gcmId) {
this.gcmId = gcmId;
}
Mysql version is
Version 5.6.22 MySQL Community Server (GPL)
I am running on Mac OS X 10.10.1 (14B25) (Yosemite)
Heres my JAX-RS class
#Path("registrations")
#Stateless
public class RegistrationResource {
#PersistenceContext
private EntityManager mEntityManager;
#POST
#Path("gcm")
public void register(final RegistrationIdJson registrationId) {
final GcmRegistraionIdentity gcmRegistraionIdentity = new GcmRegistraionIdentity();
gcmRegistraionIdentity.setRegistraionId(registrationId.getRegistrationId());
mEntityManager.persist(gcmRegistraionIdentity);
}
}
Heres the DDL for my MySql table
CREATE TABLE `gcm_registration` (
`gcm_id` int(11) NOT NULL AUTO_INCREMENT,
`registration_id` varchar(1024) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`gcm_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
I'll recommend a change in the name of id field.
Alter the table and update the column to "id". I think that "_id" is doing funny stuff on hibernate.
The solution was to replace
Hibernate Core {4.3.7.Final}
with
Hibernate Core {4.3.5.Final}
No other code or configuration changes were required

Hibernate: one-to-many and inheritance, table not getting created

I made an one-to-many relationchip between two classes (that actually works). But as soon as I add a second class which extends one of that classes the table dont get created anymore. I cant figure out why.
Shortly:
Class A got a 1-to-Many relation to Class C,
Class B extends Class A
#Entity
#Table(name = "PRODUCT")
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="discriminator",discriminatorType=DiscriminatorType.STRING )
#DiscriminatorValue(value="P")
public class Product{
#Id
#GeneratedValue
#Column(name = "PRODUCT_ID")
private int productID;
#Column(name = "ARTICLE_NUMBER")
private String articleNumber;
#Column(name = "DESCRIPTION")
private String description;
#Column(name = "TITLE")
#ManyToOne(cascade = {CascadeType.ALL})
#JoinColumn(name="MANUFACTURER_TITLE")
private Manufacturer manufacturer;
//Constructor, getter and setter
}
Subclass:
#Entity
#Table(name="PRODUCT")
#DiscriminatorValue("E")
public class Service extends Product{
#Column(name = "INTERVAL")
private int interval;
#Column(name = "UNITS")
private String units;
//Constructor, getter and setter
}
Relationchip to:
#Entity
#Table(name = "MANUFACTURER")
public class Manufacturer implements Serializable {
#Id
#Column(name = "MANUFACTURER_TITLE")
private String title;
#OneToMany(mappedBy="manufacturer")
private Set<Product> products;
//Constructor, getter and setter
}
Mapping:
<?xml version="1.0" encoding="UTF-8"?>
<!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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testshop</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">1500</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--Autocreate Tables-->
<!--property name="hibernate.archive.autodetection" value="class"/-->
<property name="hibernate.hbm2ddl.auto">create</property>
<!--Debug show sql-->
<property name="show_sql">true</property>
<!--Character Encoding for Using UTF-8 to use german special characters-->
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<!--Entity to be mapped-->
<!--Caching for performance-->
<property name="hibernate.cache.provider_class">
org.hibernate.cache.EhCacheProvider
</property>
<mapping class="test.Department"/>
<mapping class="test.Person"/>
<mapping class="test.Employee"/>
<mapping class="main.ShopConfig"/>
<mapping class="main.Logging"/>
<mapping class="product.Product"/>
<mapping class="product.Service"/>
<mapping class="manufacturer.Manufacturer"/>
</session-factory>
</hibernate-configuration>
A soon as I add the mapping for the service class it doesnt work anymore..
Edit:
If I delete the one-to-many relationchip the table gets created.. but why?!
Edit2:
Hibernate Error:
16-09-2014 10:55:14 ERROR SchemaExport:425 - HHH000389: Unsuccessful: create table PRODUCT (discriminator varchar(31) not null, PRODUCT_ID integer not null auto_increment, ARTICLE_NUMBER varchar(255), DESCRIPTION varchar(255), END_DATE tinyblob, PRICE double precision, PUBLISHED bit, QUANTITY integer, START_DATE tinyblob, TITLE varchar(255), UNLIMITED bit, WEIGHT varchar(255), INTERVAL integer, UNITS varchar(255), MANUFACTURER_TITLE varchar(255), primary key (PRODUCT_ID))
10705 [http-bio-8080-exec-12] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - HHH000389: Unsuccessful: create table PRODUCT (discriminator varchar(31) not null, PRODUCT_ID integer not null auto_increment, ARTICLE_NUMBER varchar(255), DESCRIPTION varchar(255), END_DATE tinyblob, PRICE double precision, PUBLISHED bit, QUANTITY integer, START_DATE tinyblob, TITLE varchar(255), UNLIMITED bit, WEIGHT varchar(255), INTERVAL integer, UNITS varchar(255), MANUFACTURER_TITLE varchar(255), primary key (PRODUCT_ID))
16-09-2014 10:55:14 ERROR SchemaExport:426 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTERVAL integer, UNITS varchar(255), MANUFACTURER_TITLE varchar(255), primary k' at line 1
10706 [http-bio-8080-exec-12] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTERVAL integer, UNITS varchar(255), MANUFACTURER_TITLE varchar(255), primary k' at line 1
The problem is with the field 'interval'. It is a reserved word in MySql. Change it to something else.

cannot accept a NULL value on #ID #generatedvalue JPA entity

I am trying to make a add to wish list feature for my app but I keep getting this error:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Column 'WISH_ID' cannot accept a NULL value.
Error Code: -1
Call: INSERT INTO WISHLIST (BOOK_TITLE, CUSTOMER_ID) VALUES (?, ?)
bind => [2 parameters bound]
Query: InsertObjectQuery(dukesbookstore.entity.Wishlist[ wishId=null ])
ENTITY class:
#Entity
#Table(name = "WISHLIST")
#XmlRootElement
#NamedQueries(
{
#NamedQuery(name = "Wishlist.findByCustomerId", query = "SELECT w FROM Wishlist w WHERE w.customerId = :customerId"),
})
public class Wishlist implements Serializable
{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "WISH_ID")
private Integer wishId;
#Column(name = "CUSTOMER_ID")
private Integer customerId;
#Size(max = 35)
#Column(name = "BOOK_TITLE")
private String bookTitle;
public Wishlist()
{
}
public Integer getCustomerId()
{
return customerId;
}
public void setCustomerId(Integer customerId)
{
this.customerId = customerId;
}
public String getBookTitle()
{
return bookTitle;
}
public void setBookTitle(String bookTitle)
{
this.bookTitle = bookTitle;
}
}
and this is the code for creating a new wish:
public void createWishlist(String title,int cust_id)
{
Wishlist newWish = new Wishlist();
newWish.setBookTitle(title);
newWish.setCustomerId(cust_id);
em.persist(newWish);
}
I tried to look at other similar problems but they involves hibernate which i am not using. I have also tried various generation strategy such as AUTO,SEQUENCE,TABLE but all failed. I also have another entity named customer which is exactly same but it works fine though its created from a form.
Changing to AUTO generates this error:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'SEQUENCE' does not exist.
Error Code: -1
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
root cause
java.sql.SQLSyntaxErrorException: Table/View 'SEQUENCE' does not exist.
root cause
org.apache.derby.client.am.SqlException: Table/View 'SEQUENCE' does not exist.
Persistence.xml incase relevant
<?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="myStorePU" transaction-type="JTA">
<jta-data-source>mydb</jta-data-source>
<class>myStore.entity.Book</class>
<class>myStore.entity.Customer</class>
<class>myStore.entity.Wishlist</class>
<properties>
<property name="javax.persistence.jdbc.user" value="APP"/>
<property name="javax.persistence.jdbc.password" value="APP"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
Finally it is working now,
firstly, i had to delete the table that I created from netbeans db creation tool, which had a creation code like this, as seen by using "grab structure"
create table "APP".WISHLIST
(
WISH_ID NUMERIC(5) not null primary key,
CUSTOMER_ID NUMERIC(5),
BOOK_TITLE VARCHAR(100)
)
secondly, I added this code into my persistence.xml file
<property name="eclipselink.ddl-generation" value="create-tables"/>
This solved the problem as it created the table by it self, which have different creation code, as seen from its grab structure from auto creation:
create table "APP".WISHLIST
(
WISH_ID INTEGER default GENERATED_BY_DEFAULT not null primary key,
CUSTOMER_ID NUMERIC(5),
BOOK_TITLE VARCHAR(100)
)
So, basically should let netbeans create the table itself from entity but i was using "Create entity from table" features, for that i had to create the tables first in netbeans gui.
Thank you #Geziefer for all the help, I learned quite a bit from your help too.
This might be a "Non nullable attributes" in JPA single-table-inheritance problem. It might help and doesn't hurt to specify
#JoinTable(name = "[some join table name]",
joinColumns = {#JoinColumn(name = "[some ID column name]")},
inverseJoinColumns = {#JoinColumn(name = "[some different ID column name]")})

Categories

Resources