I'm currently trying to create a many to many mapping using eclipselink. Please note that for this specific example no table to resolve the relation is used (I kwon that this is not a good practice but it is necassary for this specific example).
I've created a database schema and the tables employee3 and insurance to map. The employee table holds a column called insurance_id which is part of the primary key in order to create the mapping. Same goes for insurance with employee_id.
Now for the code:
Here is the code for the two classes:
First off Employee:
#Entity
#Table(name="employee3", schema = "many_to_many")
public class EmployeeManyToMany
{
protected EmployeeManyToMany()
{
}
#Id
private int id;
private String firstName;
private String lastName;
#ManyToMany(cascade = CascadeType.PERSIST)
private Collection<InsuranceManyToMany> insurance;
public EmployeeManyToMany(int id, String firstName, String lastName)
{
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
insurance = new ArrayList<InsuranceManyToMany>();
}
.....
And Insurance:
#Entity
#Table(name = "insurance", schema = "many_to_many")
public class InsuranceManyToMany
{
#Id
#Column(name = "id")
private int insuranceId;
private String company;
#ManyToMany(mappedBy = "insurance", cascade = CascadeType.PERSIST)
private Collection<EmployeeManyToMany> employee;
protected InsuranceManyToMany()
{
}
public void addEmployee(EmployeeManyToMany emp)
{
employee.add(emp);
}
public InsuranceManyToMany(String company, int insuranceId)
{
this.insuranceId = insuranceId;
this.company = company;
employee = new ArrayList<EmployeeManyToMany>();
}
....
After I create an Employee object and add a list of insurances to it i try to persist it into the database.
Which results in the following error:
javax.persistence.RollbackException: Exception [EclipseLink-4002]
Eclipse Persistence Services - 2.7.3.v20180807-4be1041):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: null value
in column "insurance_id" violates not-null constraint
Detail: Failing row contains (1, hans, test, null).
Error Code: 0
Call: INSERT INTO many_to_many.employee3 (ID, FIRSTNAME, LASTNAME) VALUES
(?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(swd_ws18_06_Tag3.EmployeeManyToMany#88d98e)
I have no idea why this occures since the values are never null.
Any help is appreciated!
BR
Simon
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 :)
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
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.
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.