I’m trying to configure an existing Spring Boot application to use an Oracle12c database, and I’ve got a problem with Identity columns.
Oracle12c supports identities natively, and i set the strategy as IDENTITY, but hibernate seems to ignore my identity column and try to use
select hibernate_sequence.nextval from dual
I hope someone can help me.
Thanks
This is the log:
Hibernate: select userlogini0_.id as id1_0_, userlogini0_.created_date as created_date2_0_, userlogini0_.register_number as register_number3_0_, userlogini0_.session_id as session_id4_0_, userlogini0_.session_status as session_status5_0_, userlogini0_.updated_date as updated_date6_0_, userlogini0_.user_bank as user_bank7_0_, userlogini0_.user_name as user_name8_0_, userlogini0_.user_structure as user_structure9_0_ from user_login_info userlogini0_ where userlogini0_.register_number=? and userlogini0_.user_name=? and userlogini0_.user_bank=? and userlogini0_.user_structure=? and userlogini0_.session_status=?
Hibernate: insert into user_login_info (created_date, register_number, session_id, session_status, updated_date, user_bank, user_name, user_structure) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: select hibernate_sequence.nextval from dual
2021-03-03 20:39:23.707 WARN 8 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 2289, SQLState: 42000
2021-03-03 20:39:23.707 ERROR 8 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-02289: sequence does not exist
2021-03-03 20:39:23.724 ERROR 8 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/be-profiling-clm] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
oracle.jdbc.OracleDatabaseException: ORA-02289: sequence does not exist
These are my configs:
org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
This is one of the tables:
CREATE TABLE user_login_info
(
id NUMBER(19,0) GENERATED ALWAYS AS IDENTITY INCREMENT BY 1 START WITH 1 NOT NULL ,
created_date TIMESTAMP (6) NOT NULL ,
register_number VARCHAR2(255 CHAR) NOT NULL ,
session_id VARCHAR2(255 CHAR) NOT NULL ,
session_status VARCHAR2(255 CHAR) NOT NULL ,
updated_date TIMESTAMP (6) NOT NULL ,
user_structure VARCHAR2(255 CHAR) NOT NULL ,
PRIMARY KEY (id)
);
and this is my entity:
#Data
#Entity
#Table(name = "user_login_info")
public class UserLoginInfo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false, updatable = false)
private Long id;
#Column(name = "REGISTER_NUMBER", nullable = false, updatable = false)
private String registerNumber;
#Column(name = "USER_NAME", nullable = false, updatable = false)
private String userName;
#Column(name = "USER_STRUCTURE", nullable = false, updatable = false)
private String userStructure;
#Column(name = "SESSION_ID", unique = true, nullable = false, updatable = false)
private String sessionId;
#Column(name = "SESSION_STATUS", nullable = false)
#Enumerated(EnumType.STRING)
private SessionStatus sessionStatus;
#Column(name = "CREATED_DATE", nullable = false, updatable = false)
private LocalDateTime createdDate;
#Column(name = "UPDATED_DATE", nullable = false)
private LocalDateTime updatedDate;
}
Related
i'm trying to execute this query inside the spring boot repository class , but console shows the error ' column id not found ' also the postman shows:
"status": 500,
"error": "Internal Server Error",
"message": "could not execute query; SQL [SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query",
QUERY REPOSITORY
#Query(nativeQuery=true, value="SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= :year")
public List<User> findALLUserByyear(#Param("year") String year);
CONTROLLER
#GetMapping(value="/etablissementAlls/{year}")
public EtablissementDto EtabDTOALL(#PathVariable String year) {
EtablissementDto a = new EtablissementDto();
a.setUsers(userRepository.findALLUserByyear(year));
return a;
}
Stack Trace
2021-05-05 11:14:17.600 WARN 5240 --- [nio-8020-exec-2] org.club.config.JwtRequestFilter : JWT Token does not begin with Bearer String
2021-05-05 11:14:17.604 WARN 5240 --- [nio-8020-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: S0022
2021-05-05 11:14:17.604 ERROR 5240 --- [nio-8020-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'id' not found.
2021-05-05 11:14:17.606 ERROR 5240 --- [nio-8020-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [SELECT etablissement.etab_name , app_user.creatdate_time FROM etablissement JOIN app_user WHERE year(app_user.creatdate_time)= ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
java.sql.SQLException: Column 'id' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861) ~[mysql-connector-java-5.1.46.jar:5.1.46]
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1080) ~[mysql-connector-java-5.1.46.jar:5.1.46]
NOTE
I tested this query in MYSQL PHPmyAdmin, and it works fine
USER ENTITY
#Entity
#Table(name = "app_user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "is_active")
private boolean active;
#JsonIgnore
#ManyToMany(fetch = FetchType.EAGER)
#Fetch(value = FetchMode.SUBSELECT)
#JoinTable(name = "user_etablissement", joinColumns
= #JoinColumn(name = "user_id",
referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "etablissement_id",
referencedColumnName = "id"))
private List<Etablissement> etablissements;
Clarify few things:
The MYSQL PHPmyAdmin you have queried on and the service you are connecting database to are pointing to the same database server?
Have you checked manually if 'id' column is created in the tables you are querying to?
You should change your query if you have create_time field in User entity
#Query(value="SELECT u from User u where year(u.creatdate_time)=:year")
public List<User> findALLUserByyear(#Param("year") String year);
I am having self join table CATEGORY. When I am trying to delete child entries, my parent entries ae also getting deleted. I am using Oracle 19.3 Db.
Eg.
[
{
"id": 5,
"name": "parent",
"display_name": "parent",
"parent_id": 0
},
{
"id": 6,
"name": "child",
"display_name": "child",
"parent_id": 5
}
]
Upon deleting entry with 6, entry of id 5 is also getting deleted.
My Class
#Entity
#Table(name="CATEGORY")
public class Category implements Serializable {
#Id
#Column(name = "id", nullable = false, updatable = false, unique = true)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name", nullable = false, updatable = true, unique = false)
private String name;
#Column(name = "display_name", nullable = false, updatable = true, unique = false)
private String displayName;
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name="parent_id")
private Category parent;
//Setter and Getters and Constructors
Logs from Spring boot are as follow
2021-04-30 14:50:57.345 DEBUG 2588 --- [nio-8080-exec-3] org.hibernate.SQL :
delete
from
category
where
id=?
2021-04-30 14:50:57.345 TRACE 2588 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [4]
2021-04-30 14:50:57.403 DEBUG 2588 --- [nio-8080-exec-3] org.hibernate.SQL :
delete
from
category
where
id=?
2021-04-30 14:50:57.405 TRACE 2588 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [BIGINT] - [3]
2021-04-30 14:50:57.518 INFO 2588 --- [nio-8080-exec-3] c.e.c.service.impl.CategoryServiceImpl : Course category deleted with chain
You can try to look into your #Cascade annotation with hibernate. It cascades operation between related entities and it looks you are cascading all actions.
cascade={CascadeType.ALL}, which all includes CascadeType.REMOVE.
Refer: https://www.educba.com/cascade-in-hibernate/
very new to Java/Spring/Hibernate stack. I can't get the data extracted from and xlsx sheet using the apache poi to save to an mssql database. Using an in memory database, Derby, this all just works fine which leads me to believe that it has some thing to do with the data being mapped between the java class and the mssql database table.
DB:
CREATE TABLE BASICS.IncomingData.BulkRefundUpload (
id int PRIMARY KEY,
daxPaymentReference varchar(255),
amount float,
refundReason varchar(255),
invoiceId varchar(255),
processingStatus varchar(255),
retryCount int,
iglobisRequest varchar(255),
iglobisResponse varchar(255),
refundStatus varchar(255),
createDateTime date,
createdBy varchar(255),
updateDateTime date,
modifiedBy varchar(255)
)
Class:
// omitted imports
#Entity
#Table(name = "IncomingData.BulkRefundUpload")
public class Refund {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", updatable = false, nullable = false)
private int id;
#Column
private String daxPaymentReference;
#Column
private double amount;
#Column
private String refundReason;
#Column
private String invoiceId;
#Column
private String processingStatus;
#Column
private int retryCount;
#Column
private String iglobisRequest;
#Column
private String iglobisResponse;
#Column
private String refundStatus;
#Column
#CreationTimestamp
private Date createDateTime;
#Column
private String createdBy;
#Column
#UpdateTimestamp
private Date updateDateTime;
#Column
private String modifiedBy;
// no arg constructor
public Refund() {}
// regular constructor
public Refund(String daxPaymentReference, double amount, String refundReason, String invoiceId, String processingStatus, int retryCount, String iglobisRequest, String iglobisResponse, String refundStatus, String createdBy, String modifiedBy) {
super();
this.daxPaymentReference = daxPaymentReference;
this.amount = amount;
this.refundReason = refundReason;
this.invoiceId = invoiceId;
this.processingStatus = processingStatus;
this.retryCount = retryCount;
this.iglobisRequest = iglobisRequest;
this.iglobisResponse = iglobisResponse;
this.refundStatus = refundStatus;
this.createdBy = createdBy;
this.modifiedBy = modifiedBy;
}
// getters and setters omitted
}
And the method trying to write the data, it iterates through rows in an xlsx:
List<Refund> refunds = new ArrayList<>();
sheet.rowIterator().forEachRemaining(row -> {
if(row.getRowNum() != 0) {
refunds.add(new Refund(
row.getCell(0).getStringCellValue(), //daxPaymentReference
row.getCell(1).getNumericCellValue(), //amount
row.getCell(2).getStringCellValue(), //refundReason
"",
"new",
0,
"",
"",
"",
"defaultCreatedByUser",
""
));
}
});
And finally the error:
Hibernate: select next value for hibernate_sequence
2019-01-23 13:58:04.260 WARN 1544 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 102, SQLState: S0001
2019-01-23 13:58:04.260 ERROR 1544 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Incorrect syntax near 'hibernate_sequence'.
2019-01-23 13:58:04.315 ERROR 1544 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'hibernate_sequence'.
Adding image from debugger showing the values being added to the refund object:
I have an entity that is defined with JPA annotations (only a few fields of interest shown here)
#Entity
public class Rule implements Serializable, Cloneable
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO,
generator = "SEQ_STORE")
#Column(name = "RULE_ID",
nullable = false)
private final Long id = null;
#Column(name = "CODE",
length = 25,
nullable = false)
private String code;
#Column(name = "DESCRIPTION",
length = 250,
nullable = true)
private String description;
#Column(name = "VALIDATION_FIELDS",
length = 250,
nullable = true)
private String validationFields;
#ExportField("EXPRESSION")
#Lob
#Column(name = "EXPRESSION",
nullable = true)
private String expression;
#Lob
#Column(name = "ACTION",
nullable = true)
private String action;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "PARENT_ID",
nullable = true,
foreignKey = #ForeignKey(name = "FK_XTB_RULE_2_PARENT") )
private Rule parent;
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "RULESET_ID",
nullable = false,
foreignKey = #ForeignKey(name = "FK_XTB_RULE_2_RULESET") )
private RuleSet ruleSet;
}
#Entity
public class RuleSet implements Serializable, Cloneable
{
private static final long serialVersionUID = 7982682149517239983L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO,
generator = "SEQ_STORE")
#ExportField("RULESET_ID")
#Column(name = "RULESET_ID",
nullable = false)
private final Long id = null;
#JsonIgnore
#OneToMany(mappedBy = "ruleSet",
fetch = FetchType.EAGER,
cascade = CascadeType.ALL)
#OrderBy("position")
private List<Rule> rules = new LinkedList<Rule>();
}
Then I have a method that generates a tree of these Rules (see the backreference) and puts all the rules into the List contained in the Ruleset entity.
The auto-generated DDL makes columns suitable for large expressions as the column is #Lob annotated
On Mysql and Oracle I can successfully run the code that populates the rules table (I run Bamboo tests that create DB from scratch every time). Hoever, when the testing is run oh HSQLDB, Hibernate's insert of the Ruleset object fails
2016-04-29 13:09:26,946 WARN [localhost-startStop-1] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - logExceptions - SQL Error: 3401, SQLState: 22001
2016-04-29 13:09:26,949 ERROR [localhost-startStop-1] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - logExceptions - data exception: string data, right truncation; table: XTB_RULES column: EXPRESSION
2016-04-29 13:09:39,965 ERROR [localhost-startStop-1] it.phoenix.web.data.managers.spring.ModuleManagerImpl - init - could not execute statement
org.hibernate.exception.DataException: could not execute statement
...
Caused by: org.hsqldb.HsqlException: data exception: string data, right truncation; table: XTB_RULES column: EXPRESSION
...
Caused by: org.hsqldb.HsqlException: data exception: string data, right truncation
There is an expression long 353 character in my code, I have almost found the "guilty" object.
But the problem is that even with HSQLDB the following DDL is generated
create table XTB_RULE_FUNCTIONS (RULE_FUNCTION_ID bigint identity not null,
DESCRIPTION varchar(250),
ENABLED bit not null,
EXPRESSION varchar(MAX) not null,
NAME varchar(50) not null,
OBJECT_TYPE varchar(20) not null,
POSITION bigint not null,
primary key (RULE_FUNCTION_ID));
EXPRESSION is supposed to be VARCHAR(max), so it should accommodate any string.
But my insertion still fails. I have no mean to check the actual in-memory database at the moment
Other info on the application:
Is a web application running on Tomcat
I use Bamboo CI to run tests on different databases, each loading the Spring context instead of being run in a servlet container
Part of Spring initialization is to populate, along others, the Ruleset table if data does not exist. Since Bamboo recreates DB at every run (especially in-memory one), I always need to populate rules declared programmatically somewhere in a piece of code useless to paste here
I have read this but I have checked that DDL script declares VARCHAR(max) so I don't think that applies to me
Again and again, the same code works on other DBs
Still, I need to store data larger than 255 characters
Any idea on how to fix? In my unit testing I may still comment out one of the entities, but that is only a workaround.
for 3 days, I'm stuck on this problem, I try to explain as clearly as possible:
I'm working on a software inventory management, I use EclipseLink(JPA2.0) for managing the Database.
the problem is that when I create a new invoice with related Articles
, and try to persist them, then i get a Referential integrity constraint violation Exception...
the real problem is that I generated all entities with netbeans(since I'm not familiar with the annotation)
and I can not confirm if they are correctly generated or not(but still I doubt)....
tables SQL:
CREATE TABLE fact_proforma (
idfact_proforma INT UNSIGNED NOT NULL AUTO_INCREMENT,
utilisateur_login VARCHAR(25) NOT NULL,
client_idclient INT UNSIGNED NOT NULL,
date DATE NOT NULL,
PRIMARY KEY(idfact_proforma),
FOREIGN KEY(client_idclient)
REFERENCES client(idclient)
ON DELETE NO ACTION
ON UPDATE CASCADE,
FOREIGN KEY(utilisateur_login)
REFERENCES utilisateur(login)
ON DELETE NO ACTION
ON UPDATE CASCADE
);
CREATE TABLE fact_proforma_has_article (
fact_proforma_idfact_proforma INT UNSIGNED NOT NULL,
article_idarticle VARCHAR(40) NOT NULL,
prix_ht DOUBLE NOT NULL,
qte DOUBLE NOT NULL,
remise DOUBLE NOT NULL,
marge_benef DOUBLE NOT NULL,
PRIMARY KEY(fact_proforma_idfact_proforma, article_idarticle),
FOREIGN KEY(fact_proforma_idfact_proforma)
REFERENCES fact_proforma(idfact_proforma)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY(article_idarticle)
REFERENCES article(idarticle)
ON DELETE NO ACTION
ON UPDATE CASCADE
);
CREATE TABLE article (
idarticle VARCHAR(40) NOT NULL,
libel VARCHAR(100) NOT NULL,
prix_ht DOUBLE NOT NULL,
tva_idtva DOUBLE NOT NULL,
qte DOUBLE NOT NULL,
min_qte DOUBLE NOT NULL,
marge_benef DOUBLE NOT NULL,
remise DOUBLE NOT NULL,
unite_idunite VARCHAR(10) NOT NULL,
famille_idfamille VARCHAR(50) NOT NULL,
etat CHAR(1) NOT NULL,
PRIMARY KEY(idarticle),
FOREIGN KEY(tva_idtva)
REFERENCES tva(idtva)
ON DELETE NO ACTION
ON UPDATE CASCADE,
FOREIGN KEY(famille_idfamille)
REFERENCES famille(idfamille)
ON DELETE NO ACTION
ON UPDATE CASCADE,
FOREIGN KEY(unite_idunite)
REFERENCES unite(idunite)
ON DELETE NO ACTION
ON UPDATE CASCADE
);
CREATE TABLE utilisateur (
login VARCHAR(25) NOT NULL,
pass VARCHAR(15) NOT NULL,
class CHAR(1) NOT NULL,
etat CHAR(1) NOT NULL,
PRIMARY KEY(login)
);
FactProforma.java: // "Facture Proforma" is "proforma invoice"
public class FactProforma implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "IDFACT_PROFORMA", nullable = false)
private Integer idfactProforma;
#Basic(optional = false)
#Column(name = "DATE", nullable = false)
#Temporal(TemporalType.DATE)
private Date date;
#OneToMany(cascade=CascadeType.ALL , mappedBy = "factProforma")
private List<FactProformaHasArticle> factProformaHasArticleList;
#JoinColumn(name = "UTILISATEUR_LOGIN", referencedColumnName = "LOGIN", nullable = false)
#ManyToOne(optional = false)
private Utilisateur utilisateurLogin;
#JoinColumn(name = "CLIENT_IDCLIENT", referencedColumnName = "IDCLIENT", nullable = false)
#ManyToOne(optional = false)
private Client clientIdclient;
FactProformaHasArticle.java
public class FactProformaHasArticle implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected FactProformaHasArticlePK factProformaHasArticlePK;
#Basic(optional = false)
#Column(name = "PRIX_HT", nullable = false)
private double prixHt;
#Basic(optional = false)
#Column(name = "QTE", nullable = false)
private double qte;
#Basic(optional = false)
#Column(name = "REMISE", nullable = false)
private double remise;
#Basic(optional = false)
#Column(name = "MARGE_BENEF", nullable = false)
private double margeBenef;
#JoinColumn(name = "FACT_PROFORMA_IDFACT_PROFORMA", referencedColumnName = "IDFACT_PROFORMA", nullable = false, insertable = false, updatable = false)
#ManyToOne(optional = false)
private FactProforma factProforma;
#JoinColumn(name = "ARTICLE_IDARTICLE", referencedColumnName = "IDARTICLE", nullable = false, insertable = false, updatable = false)
#ManyToOne(optional = false)
private Article article;
FactProformaHasArticlePK.java
#Embeddable
public class FactProformaHasArticlePK implements Serializable {
#Basic(optional = false)
#Column(name = "FACT_PROFORMA_IDFACT_PROFORMA", nullable = false)
private int factProformaIdfactProforma;
#Basic(optional = false)
#Column(name = "ARTICLE_IDARTICLE", nullable = false, length = 40)
private String articleIdarticle;
my code:
FactProforma factpro=new FactProforma(null, new Date());
Utilisateur user=new Utilisateur(loginActuel);
Client client=new Client(Integer.parseInt(codeClient.getText()));
java.util.List<FactProformaHasArticle> ListOfArticles =this.c.GetPanier(dtm,factpro);
factpro.setClientIdclient(client);
factpro.setFactProformaHasArticleList(ListOfArticles);
factpro.setUtilisateurLogin(user);
EntityManager em= emf.createEntityManager();
em.getTransaction().begin();
em.persist(factpro);
em.getTransaction().commit();
stack trace:
Exception in thread "AWT-EventQueue-0" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "CONSTRAINT_9A: PUBLIC.FACT_PROFORMA_HAS_ARTICLE FOREIGN KEY(FACT_PROFORMA_IDFACT_PROFORMA) REFERENCES PUBLIC.FACT_PROFORMA(IDFACT_PROFORMA)"; SQL statement:
Internal Exception: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "CONSTRAINT_9A: PUBLIC.FACT_PROFORMA_HAS_ARTICLE FOREIGN KEY(FACT_PROFORMA_IDFACT_PROFORMA) REFERENCES PUBLIC.FACT_PROFORMA(IDFACT_PROFORMA)"; SQL statement:
INSERT INTO TEST.PUBLIC.FACT_PROFORMA_HAS_ARTICLE (MARGE_BENEF, PRIX_HT, QTE, REMISE, ARTICLE_IDARTICLE, FACT_PROFORMA_IDFACT_PROFORMA) VALUES (?, ?, ?, ?, ?, ?) [23506-164]
INSERT INTO TEST.PUBLIC.FACT_PROFORMA_HAS_ARTICLE (MARGE_BENEF, PRIX_HT, QTE, REMISE, ARTICLE_IDARTICLE, FACT_PROFORMA_IDFACT_PROFORMA) VALUES (?, ?, ?, ?, ?, ?) [23506-164]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.constraint.ConstraintReferential.checkRowOwnTable(ConstraintReferential.java:345)
at org.h2.constraint.ConstraintReferential.checkRowOwnTable(ConstraintReferential.java:345)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:287)
at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:287)
at org.h2.table.Table.fireConstraints(Table.java:862)
at org.h2.table.Table.fireConstraints(Table.java:862)
at org.h2.table.Table.fireAfterRow(Table.java:879)
at org.h2.table.Table.fireAfterRow(Table.java:879)
at org.h2.command.dml.Insert.insertRows(Insert.java:126)
at org.h2.command.dml.Insert.update(Insert.java:84)
at org.h2.command.dml.Insert.insertRows(Insert.java:126)
at org.h2.command.CommandContainer.update(CommandContainer.java:73)
at org.h2.command.dml.Insert.update(Insert.java:84)
at org.h2.command.Command.executeUpdate(Command.java:226)
at org.h2.command.CommandContainer.update(CommandContainer.java:73)
at org.h2.server.TcpServerThread.process(TcpServerThread.java:325)
at org.h2.command.Command.executeUpdate(Command.java:226)
at org.h2.server.TcpServerThread.run(TcpServerThread.java:146)
at java.lang.Thread.run(Thread.java:722 at org.h2.server.TcpServerThread.process(TcpServerThread.java:325)
)
Error Code: 23506
Call: INSERT INTO TEST.PUBLIC.FACT_PROFORMA_HAS_ARTICLE (MARGE_BENEF, PRIX_HT, QTE, REMISE, ARTICLE_IDARTICLE, FACT_PROFORMA_IDFACT_PROFORMA) VALUES (?, ?, ?, ?, ?, ?)
at org.h2.server.TcpServerThread.run(TcpServerThread.java:146)
bind => [6 parameters bound]
at java.lang.Thread.run(Thread.java:722)
tomorrow I will try with another DBMS, to avoid conflict...
PS: Im Sorry for french language..I have no choice.
UPDATE:
its worked :
EntityManager em= emf.createEntityManager();
em.getTransaction().begin();
em.persist(fact);
em.flush();
for(FactProformaHasArticle couple: estComposeFacture)
{
couple.getFactProformaHasArticlePK().setFactProformaIdfactProforma(fact.getIdfactProforma());
em.persist(couple);
}
em.getTransaction().commit();
You already have a solution but I thought I'd mention the reason why it works is because you have the primary key field controled through the EmbeddedId's basic mapping - so even though you may have set the relationship before persisting, the pk field will be null until the embeddedId's articleIdarticle is set with a value manually. This is the problem with having the "ARTICLE_IDARTICLE" mapped twice - both mappings should be maintained by the application, and the pk value needs to be available before you persist FactProformaHasArticle.
JPA 2.0 makes this setup a bit easier, as you can use the #MapsId annotation on the relationship to show that it controls the embeddedId's basic mapping - so you only need to set the relationship and have JPA set the field for you. Or you can remove the embeddedId, use the object as a PKclass and mark the relationship with #Id directly as described here:
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0
Using this will allow you to remove the flush call, as JPA will set the pk values for you.
EDITED POST:
You need to make sure you have the relationship between FactProformaHasArticle and FactProforma is fully referenced. I suspect you need to have something like this before you can persist:
List<FactProformaHasArticle> ListOfArticles =this.c.GetPanier(dtm,factpro)
for(FactProformaHasArticle fpha: ListOfArticles) {
fpha.setFactProforma(factpro);
}
(Note: having lowercase for first letter of member variables would be nicer, i.e.
listOfArticles instead of ListOfArticles etc)
INITIAL POST (in case it is also valid for your case):
Have you tried to remove the optional=false and nullable=false from the annotations of primary keys? I used to have issues with it: JPA wouldn't allow to do MyEntity me=new MyEntity(null); because of that. Try something like:
public class FactProforma implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
// removed:#Basic(optional = false)
#Column(name = "IDFACT_PROFORMA") // removed: , nullable = false)
private Integer idfactProforma;
// rest should be ok
}