JPA/MySql issue - java

I am building JPA based application using mysql and ecliselink.I have very strange issue when try to insert stuff into my database.I am able to insert data into single table but when it comes to one-to-may and vice versa something goes wrong.Currently I have 2 main and 1 reference table(it holds the foreign keys of the other two tables).It is strange because I dont have "sequence" in my database table When I try to insert data into any of my tables I get this exception:
[EL Info]: 2012-03-15 17:52:28.64--ServerSession(18621340)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
[EL Info]: 2012-03-15 17:52:29.23--ServerSession(18621340)--file:/D:/git-eclipse/Martin/reference/build/classes/_reference login successful
[EL Warning]: 2012-03-15 17:52:29.389--ClientSession(31843177)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eclipse1.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="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eclipse1.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="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
[EL Info]: 2012-03-15 17:52:29.394--ServerSession(18621340)--file:/D:/git-eclipse/Martin/reference/build/classes/_reference logout successful
Exception in thread "main" java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManager.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.verifyOpen(EntityManagerImpl.java:1665)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.close(EntityManagerImpl.java:1529)
at OneToManyRelation.main(OneToManyRelation.java:47)
I am posting one class only because others are quite similar
#Entity
#Table(name="category")
public class Category {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="CategoryID")
private int CategoryID;
/**
* #return the id
*/
public int getId() {
return CategoryID;
}
/**
* #param id the id to set
*/
public void setId(int CategoryID) {
this.CategoryID = CategoryID;
}
#Column(name="category", nullable=false, length=50, insertable=true)
private String category;
/**
* #return the category
*/
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
#OneToMany(cascade=CascadeType.ALL)
#JoinTable(name = "templateemail", joinColumns = {
#JoinColumn(name="categoryId", unique = true)
},
inverseJoinColumns = {
#JoinColumn(name="templateId")
}
)
private Set<Template> template;
/**
*
*/
public Set<Template> getChildren() {
return template;
}
/**
*
*/
public void setChildren(Set<Template> template) {
this.template = template;
}
}
Do you have any idea what is wrong with my code?
Thanks in advance

Seeing the code would help finding what's wrong with it. But by judging on the error message only, it seems you chose to use a sequence or table generator, and that this generator relies (by default) on a table named sequence, that doesn't exist in the database.
Create this table, or configure the generator to use an existing table, or change the ID generator.

Related

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]")})

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null?

im having difficulty inserting datas to database table from java classes. I'm getting "Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null"... I did some digging and couldn't figure it out. Let me post my codes... before that i explain what i want to do... This project contains Servlet class,JSP , and java classes. I'm using JSP html Form to get datas and records them to into a database. Codes here...
#Entity
#Table(name="\"Leave\"")
public class Leave implements Serializable{
/**
*
*/
private static final long serialVersionUID = 9088190714759727299L;
#Id
#Column(name="id",nullable=false,updatable=false)
private Long id;
//#OneToOne(mappedBy=)
#GeneratedValue(strategy = GenerationType.AUTO)
#JoinColumn(name = "person_id",referencedColumnName="id")
private Person person;
//#Enumerated(LeaveType)
#Column(name="leavetype")
private LeaveType leavetype;
#Temporal(TemporalType.DATE)
#Column(name="prepdate")
private Date prepdate;
#Temporal(TemporalType.DATE)
#Column(name="startdate")
private Date startdate;
#Temporal(TemporalType.DATE)
#Column(name="enddate")
private Date enddate;
#Temporal(TemporalType.DATE)
#Column(name="oldstartdate")
private Date oldStartdate;
#Temporal(TemporalType.DATE)
#Column(name="oldenddate")
private Date oldEnddate;
#Column(name="workday")
private String workday;
#Column(name="calendarday")
private String calendarday;
#Column(name="reason")
private String reason;
getters setters....
#Entity
#Table(name="\"Person\"")
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2532993385565282772L;
#Id
#Column(name="id",nullable=false,updatable=false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String surname;
private String sskno;
private String workstartdate;
private String address;
private String telno;
#OneToMany
private List<Leave> leaves;
AND MY SERVLET CLASS IS....
#WebServlet("/LeaveServlet")
public class LeaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNIT_NAME = "EmployeeLeaveForm";
private static EntityManagerFactory emf;
public LeaveServlet() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager entityManager = emf.createEntityManager();
try {
PrintWriter out = response.getWriter();
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/FormInterface.jsp");
Person person = new Person();
Leave leave = new Leave();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String choosenType = request.getParameter("leavetype");
// LEAVING
// TYPES---------------------------------------------------------------------------------------------------
if (choosenType == null) {
request.setAttribute("leaveTypeError",
"Izin turunu giriniz.");
requestDispatcher.forward(request, response);
return;
}
else if (choosenType.equals(LeaveType.ANNUAL.toString())) {
leave.setLeavetype(LeaveType.ANNUAL);
} else if (choosenType.equals(LeaveType.MARRIAGE.toString())) {
leave.setLeavetype(LeaveType.MARRIAGE);
} else if (choosenType.equals(LeaveType.FEEDING.toString())) {
leave.setLeavetype(LeaveType.FEEDING);
} else if (choosenType.equals(LeaveType.MEDICAL.toString())) {
leave.setLeavetype(LeaveType.MEDICAL);
} else if (choosenType.equals(LeaveType.MATERNITY.toString())) {
leave.setLeavetype(LeaveType.MATERNITY);
} else if (choosenType.equals(LeaveType.OTHER.toString())) {
leave.setLeavetype(LeaveType.OTHER);
leave.setReason(request.getParameter("reason"));
if (leave.getReason() != null) {
} else if (leave.getReason() == null) {
request.setAttribute("errorNoReason",
"Please enter a reason");
requestDispatcher.forward(request, response);
return;
}
} else if (choosenType.equals(LeaveType.UNPAID.toString())) {
leave.setLeavetype(LeaveType.UNPAID);
leave.setReason(request.getParameter("reason"));
if (leave.getReason() != null) {
} else if (leave.getReason() == null) {
request.setAttribute("errorNoReason",
"Please enter a reason");
requestDispatcher.forward(request, response);
return;
}
}
// PASSING PARAMETERS TO LOCAL
// VARIABLES---------------------------------------------------------------------------
String prepdate = dateFormat.format(date);
String startdate = request.getParameter("startdate");
String enddate = request.getParameter("enddate");
String oldStartdate = request.getParameter("oldStartdate");
String oldEnddate = request.getParameter("oldEnddate");
person.setName(request.getParameter("name"));
person.setSurname(request.getParameter("surname"));
person.setSskno(request.getParameter("sskno"));
person.setworkStartdate(request.getParameter("workStarted")); // DBden
person.setAddress(request.getParameter("address"));
person.setTelno(request.getParameter("telephone"));
leave.setCalendarday(request.getParameter("calendarday"));
leave.setWorkday(request.getParameter("workday"));
leave.setPrepdate(dateFormat.parse(prepdate));
leave.setStartdate(dateFormat.parse(startdate));
leave.setEnddate(dateFormat.parse(enddate));
leave.setOldStartdate(dateFormat.parse(oldStartdate));
leave.setOldEnddate(dateFormat.parse(oldEnddate));
// Checking the consistency of the
// time----------------------------------------------------------------------------
if (((leave.getEnddate() != null) && (leave.getOldEnddate() != null))) {
entityManager.getTransaction().begin();
entityManager.persist(leave);
entityManager.getTransaction().commit();
//db den return
//info
}
else {
if (leave.getEnddate() == null) {
request.setAttribute("errorMessage1", "Please enter dates correctly");
}
if (leave.getOldEnddate() == null) {
request.setAttribute("errorMessage2", "Please enter date correctly");
}
requestDispatcher.forward(request, response);
}
} catch (Throwable exc) {
System.out.println(exc);
}
finally {
// Close the database connection:
if (entityManager.getTransaction().isActive())
entityManager.getTransaction().rollback();
entityManager.close();
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
And errors...
[EL Info]: 2013-07-29 10:05:47.872--ServerSession(76232710)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-07-29 10:05:48.207--ServerSession(76232710)--file:/C:/Users/VAIO/Desktop/workspace - Kopya/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/EmployeeLeaveForm/WEB-INF/classes/_EmployeeLeaveForm login successful
[EL Warning]: 2013-07-29 10:05:48.292--UnitOfWork(1213364484)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO `Leave` (id, calendarday, enddate, leavetype, oldenddate, oldstartdate, prepdate, reason, startdate, workday, person_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(com.eteration.leavesystem.model.Leave#4fff5f4f)
javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null
Error Code: 1048
Call: INSERT INTO `Leave` (id, calendarday, enddate, leavetype, oldenddate, oldstartdate, prepdate, reason, startdate, workday, person_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(com.eteration.leavesystem.model.Leave#4fff5f4f)
I also use mysql and i created a database table.
WHY am I getting these exceptions.. And seriously i did digging but nothing work for me pls help me thanks...
EDIT-
[EL Info]: 2013-07-29 11:05:56.944--ServerSession(624062858)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-07-29 11:05:57.283--ServerSession(624062858)--file:/C:/Users/VAIO/Desktop/workspace - Kopya/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/EmployeeLeaveForm/WEB-INF/classes/_EmployeeLeaveForm login successful
[EL Warning]: 2013-07-29 11:05:57.362--ClientSession(72318077)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eteration.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="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'eteration.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="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
It seems you try to persist your entity and its id remains null. That's why your get a constraint violation error.
To simply solve this error I suggest you to try create your database table using auto-incrementation option on your id. It should solve your problem, I guess.
It means supply data(from some source and of a type that matches the db field type for "id") for the "id" column to insert into the database with the call. Somewhere you are not supplying and "id" data to the query in your code.
Add
#GeneratedValue(strategy = GenerationType.AUTO)
to your Leave ID
#Id
#Column(name="id",nullable=false,updatable=false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
or create Leave constructor with Long Id arg to set your id. So, you wont be able to create Leave instance with id set to null.
Is it missing GeneratedValue annotation in id field?
If you use AUTO generation, the id generation will be depend on Persistence Provider.
You might need to set auto increment for primary key.
#Entity
#Table(name="Leave")
public class Leave implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id",nullable=false,updatable=false)
private Long id;
#OneToOne
#GeneratedValue(strategy = GenerationType.AUTO) --> remove this code
#JoinColumn(name = "person_id", referencedColumnName="id")
private Person person;
}
You are not setting the id in your code and you are not telling your JPA provider to generate it either.
You can use the #GeneratedValue annotation to tell your JPA provider to generate your id.
Here is an example
I figure it out my problem thank you guys for help. I solved my problem in that way... eclipselink needs sequence table on my database and i created one then it works... Thank you again :)

JPA OneToMany using Inheritance

I have the following classes:
Hardware.java
#Entity
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Hardware{
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
private long id;
private String serialnumber;
#OneToMany (mappedBy="hardware")
private List<Equipment> equipments;
}
Computer.java
#Entity
public class Computer extends Hardware {
private String hostname;
private String macAdress;
private String ipNumber;
public Computer(){
super();
}
public Computer(String serialnumber, String hostname,
String macAdress, String ipNumber) {
super(serialnumber);
this.hostname = hostname;
this.macAdress = macAdress;
this.ipNumber = ipNumber;
}
}
NetworkDeivce.java
#Entity
public class NetworkDevice extends Hardware {
private String hostname;
private String ipAdress;
public NetworkDevice(){
super();
}
public NetworkDevice(String serialnumber, String hostname,
String ipAdress) {
super(serialnumber);
this.hostname = hostname;
this.ipAdress = ipAdress;
}
}
And now the class that is mapped to the Hardware Class:
Equipment.java
#Entity
public class Equipment {
public Equipment(){
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String serialnumber;
private String info;
#ManyToOne (fetch=FetchType.EAGER)
#JoinColumn(name="HW_ID")
private Hardware hardware;
}
Now if I add a Equipment to a Computer it all works finde, but if I try to add Equipment to a NetworkDevice I get this Error:
Internal Exception:
Internal Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`inventorytool_beta`.`EQUIPMENT`, CONSTRAINT `FK_EQUIPMENT_HW_ID` FOREIGN KEY (`HW_ID`) REFERENCES `COMPUTER` (`ID`))
Error Code: 1452
Call: INSERT INTO EQUIPMENT (INFO, SERIALNUMBER, HW_ID) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(domain.hardware.Equipment#600a620d)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
at main.dbTest(main.java:74)
at main.main(main.java:18)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`inventorytool_beta`.`EQUIPMENT`, CONSTRAINT `FK_EQUIPMENT_HW_ID` FOREIGN KEY (`HW_ID`) REFERENCES `COMPUTER` (`ID`))
Error Code: 1452
Call: INSERT INTO EQUIPMENT (INFO, SERIALNUMBER, HW_ID) VALUES (?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(domain.hardware.Equipment#600a620d)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:851)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:913)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`inventorytool_beta`.`EQUIPMENT`, CONSTRAINT `FK_EQUIPMENT_HW_ID` FOREIGN KEY (`HW_ID`) REFERENCES `COMPUTER` (`ID`))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
So I think it's a problem with the inheritance... I'm not very good at JPA..
Thanks in advance.
Have a look at the schema that was generated. You should had three different tables for hardware, due to your inheritance strategy: one for Hardware, one for Computer and one fon NetworkDevice. The problem is that HW_ID can only reference one table. Here your JPA provider chose Computer, probably because it's first in alphabetical order, but it can't handle all three classes.
Consider using another inheritance strategy, like JOIN.
Check the code where you insert Equipment to a NetworkDevice. It looks like HW_ID does not exists in the master-table(Hardware). Because it is trying to insert nonexistent Master-Table HW_ID as foreign-Key in child table(Equipment).
Regards,
Ravi
Yes it comes from your inheritance strategy. You can't use #GeneratedValue(strategy=GenerationType.IDENTITY) with table_per_class.
See Java/Hibernate JPA: InheritanceType.TABLE_PER_CLASS and IDs

error while trying to add new value for JPA table

Im using JPa API's and its work well ,I have tried to add new member/column to the class(table) and when I was tried to add data for it works fine but in the commit part I get dump with the following error
Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'DOUBLE1' is not a column in table or VTI 'TEST.PERSON'.
Error Code: 20000
Call: INSERT INTO PERSON (ID, DOUBLE1, FIRSTNAME, LASTNAME, NONSENSEFIELD) VALUES (?, ?, ?, ?, ?)
bind => [5 parameters bound]
But in the table person I have added the member double1 as follows
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private String id;
private String firstName;
private String lastName;
private double double1;
....
public double getDouble1() {
return double1;
}
public void setDouble1(double double1) {
this.double1 = double1;
}
What am i missing here?
There is obviously no column DOUBLE1 in the database table VTI 'TEST.PERSON'. Adding a new field to a JPA entity does not automatically make it appear in the database as well.

'ALTER TABLE' cannot be performed because table does not exist

I'm using JPA 2 with Eclipselink 2 and a Derby in memory db for my tests. When I start my little test programm I get the following exception:
[EL Warning]: 2010-08-12 17:17:44.943--ServerSession(948252856)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'ALTER TABLE' cannot be performed on 'ARTICLE_ARTICLE' because it does not exist.
Error Code: 30000
Call: ALTER TABLE ARTICLE_ARTICLE DROP CONSTRAINT RTCLrtclsRltdTThsD
Query: DataModifyQuery(sql="ALTER TABLE ARTICLE_ARTICLE DROP CONSTRAINT RTCLrtclsRltdTThsD")
If I try the same with HyperSQL (hsqldb) I get:
[EL Warning]: 2010-08-12 17:47:33.179--ServerSession(1925661675)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: user lacks privilege or object not found: ARTICLE_ARTICLE
Error Code: -5501
Call: ALTER TABLE ARTICLE_ARTICLE DROP CONSTRAINT FK_ARTICLE_ARTICLE_articlesRelatedToThis_ID
Query: DataModifyQuery(sql="ALTER TABLE ARTICLE_ARTICLE DROP CONSTRAINT FK_ARTICLE_ARTICLE_articlesRelatedToThis_ID")
The table generation strategy is "drop-and-create", so why does Eclipselink tell me that a table would not exist?
Or is something wrong with my example class?
#Entity
public class Article implements Serializable {
#Id #GeneratedValue
private int id;
private String title;
#ManyToMany(mappedBy = "relatedArticles")
private Set<Article> articlesRelatedToThis = new HashSet<Article>();
#ManyToMany(cascade = CascadeType.PERSIST)
private Set<Article> relatedArticles = new HashSet<Article>();
public Article() {}
public Article(String title) {
this.title = title;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Article> getRelatedArticles() {
return relatedArticles;
}
public void addRelatedArticle(Article related) {
relatedArticles.add(related);
}
public void removeRelatedArticle(Article related) {
relatedArticles.remove(related);
}
#PreRemove
public void preRemove() {
for(Article article : articlesRelatedToThis)
article.removeRelatedArticle(this);
}
}
The table generation strategy is "drop-and-create", so why does Eclipselink tell me that a table would not exist?
EcliseLink starts by dropping table constraints (the alter statement you're seeing), then the tables, and then recreate everything. Since you are using an in-memory database, there is actually nothing to drop and EclipseLink reports the failed attempts as a warning. Just ignore them.

Categories

Resources