I'm trying to add a field with special characters like "Patrícia" or "José" and since that field is a Name I used a regex pattern from
^[a-zA-Z\u00C0-\u00FF]+
tested in https://regexr.com/
This is the field inside the user model:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private Integer id;
(etc)
#Column(name = "name")
#Pattern(regexp = " ^[a-zA-Z\u00C0-\u00FF]+" , message = "{user.name.pattern}")
#NotEmpty(message = "{user.name.empty}")
#Size(min=1, max=40, message = " {user.name.size}")
private String name;
(getters/setters/constructor)
If I add Patricia or Jose, for example the validation succeeds and the user gets inserted. The regex seems ok in the regExr using those names...
This is the error I get:
Hibernate: insert into user (f1, f2, f3, last_name, name, f6, f7, user_id) values (?, ?, ?, ?, ?, ?, ?, ?)
2018-05-22 17:40:34.622 WARN 8475 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1062, SQLState: 23000
2018-05-22 17:40:34.623 ERROR 8475 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry '3' for key 'PRIMARY'
2018-05-22 17:40:34.624 INFO 8475 --- [nio-8080-exec-3] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2018-05-22 17:40:34.626 ERROR 8475 --- [nio-8080-exec-3] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2018-05-22 17:40:34.664 ERROR 8475 --- [nio-8080-exec-3] 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.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3' for key 'PRIMARY'
What does the primary key has to do with the name validation?
What can I be doing wrong?
Thank you,
Eunito.
Related
Method in Dao Interface
#RegisterRowMapper(MapMapper.class)
#SqlQuery(
"SELECT Table1.tenantId,Table1.sacTenantId, sacLogId,currentStep,status from Table1 inner join Table2 on Table1.tenantId = Table2.tenantId where <if(tenantId)>Table1.tenantId = :tenantId and<endif> Table2.status = 'FAILED'")
List<Map<String, Object>> getTenantFailedJobDetails(#Define("tenantId") #Bind("tenantId") String tenantId);
Error trace:
"level":"ERROR","categories":[],"msg":"Servlet.service() for servlet
[dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is
org.jdbi.v3.core.statement.UnableToCreateStatementException: Error
rendering SQL template: 'SELECT Table1.tenantId,Table1.sacTenantId,
sacLogId,currentStep,status from Table1 inner join Table2 on
Table1.tenantId = Table2.tenantId where <if(tenantId)>Table1.tenantId
= :tenantId and Table2.status = 'FAILED'' [statement:"null", arguments:{positional:{0:DUMMY-TENANT}, named:{tenantId:DUMMY-TENANT},
finder:[]}]] with root
cause","stacktrace":["org.jdbi.v3.core.statement.UnableToCreateStatementException:
Undefined attribute for token '' [statement:"null",
arguments:{positional:{0:DUMMY-TENANT}, named:{tenantId:DUMMY-TENANT},
finder:[]}]"
What could be wrong with the if condition?
To make if condition in jdbi query work I added annotation #UseStringTemplateEngine of package org.jdbi.v3.stringtemplate4 to the Dao method
If tenandId is not null then where clause will be
Table1.tenantId = :tenantId and Table2.status = 'FAILED'
else where clause will be just
Table2.status = 'FAILED'
One more information to add, for the else part annotation #AllowUnusedBindings package org.jdbi.v3.sqlobject.customizer is required
The syntax you posted is stringtemplate4, so you need to use the stringtemplate 4 engine (which you select with the annotation that you posted). Otherwise you end up with the default engine which does support only very simply substitutions (and not st4 syntax).
I'm working with APEX 19.2. I'm trying to handle constraint errors with an error handling function.
I have an interactive grid built on a table with unique constraint. I created constraint_lookup that matches constraint name with message.
I created a function mainly based on Oracle Doc example (that is for example in package wwv_flow_error_api)
The only thing I changed was the display location:
l_result.display_location := case
when l_result.display_location =
apex_error.c_on_error_page then
apex_error.c_inline_with_field_and_notif
else
l_result.display_location
end;
Right now when I'm trying to add a value with non-unique value I get a message in notification like I wanted, but I don't know how to handle it to show error in notification and with the field (like in apex validation, where you can associate item)
I tried to list all apex_error attributes and I get
p_error
message ORA-00001: naruszono więzy unikatowe (#CONSTAINT_NAME#)
additional_info
ORA-00001: naruszono więzy unikatowe (#CONSTAINT_NAME#)
display_location ON_ERROR_PAGE
association_type
page_item_name
region_id
column_alias
row_num
model_instance_id
model_record_id
apex_error_code
original_message
original_additional_info
ora_sqlcode -1
ora_sqlerrm ORA-00001: naruszono więzy unikatowe (#CONSTAINT_NAME#)
error_backtrace
error_statement "ADM"
l_result
message #ERROR MESSAGE#
additional_info ORA-00001: naruszono wiezy unikatowe (#CONSTAINT_NAME#)
display_location INLINE_WITH_FIELD_AND_NOTIFICATION
page_item_name
column_alias
How to connect field from constraint with the field in interactive grid?
You should add p_page_item_name parameter. For example:
p_message => 'Employee name cannot be null',
p_display_location => apex_error.c_inline_with_field_and_notif ,
p_page_item_name => 'P10_NAME');
Can you update your error handling function with the following code please. It adds additional debug statements.
if p_error.ora_sqlcode in (-1, -2091, -2290, -2291, -2292) then
l_constraint_name := apex_error.extract_constraint_name (
p_error => p_error );
apex_debug.info( 'Raised constraint error: %s', l_constraint_name );
begin
select message
into l_result.message
from constraint_lookup
where constraint_name = l_constraint_name;
apex_debug.info( 'Constraint found, new message: %s', l_result.message );
exception when no_data_found then
apex_debug.info( 'Constraint not found in constraint_lookup' );
end;
end if;
Run your application in debug mode and reproduce the error. After that you can use View Debug to find out if your constraint_lookup entry is actually used.
When executing the controller method I receive this log:
OBJECT: [Field error in object 'catalog' on field 'name': rejected value [safasf]; codes [Pattern.catalog.name,Pattern.name,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [catalog.name,name]; arguments []; default message [name],[Ljavax.validation.constraints.Pattern$Flag;#5f32f731,org.springframework.validation.beanvalidation.SpringValidatorAdapter$ResolvableAttribute#2180fe7e]; default message [muss auf Ausdruck "[A-Za-z]" passen]]
Regex: [A-Za-z]
Input: safasf
The code:
...
#NotNull
#Size(min=1, max=8)
#Pattern(regexp = "[A-Za-z]")
private String name;
...
The controller:
#PostMapping(ADD_CATALOG)
public String addCatalog(#Valid #ModelAttribute Catalog catalog, BindingResult result){
if(result.hasErrors()){
logAction("addCatalog", "Validation of "+catalog.getName()+" failed: ", result.getAllErrors().toString());
return "redirect:/catalog/addCatalog/";
}
catalogProviderComponent.addOrUpdateCatalogEntity(catalogComponent.catalog2catalogEntity(catalog));
logAction("addCatalog","catalog", catalog);
return "redirect:/catalog/addCatalog/";
}
When I go to regex101.com everything seems to be fine. Beside that I tried few regex but none seem to work out properly.
To allow for one or more lowercase or uppercase letter, you should append + to the end of the pattern:
#NotNull
#Size(min=1, max=8)
#Pattern(regexp = "[A-Za-z]+")
private String name;
I have installed FPNTagBundle via composer.
$tagArray=array('uno','due');
$tagManager = $this->get('fpn_tag.tag_manager');
$tagsObj = $tagManager->loadOrCreateTags($tagArray);
$tagManager->replaceTags($tagsObj,$entity);
$em->persist($entity);
$em->flush();
I get this error that avoid tag to persist:
An exception occurred while executing 'INSERT INTO Tag (name, slug,
created_at, updated_at) VALUES (?, ?, ?, ?)' with params
{"1":null,"2":"uno","3":null,"4":null}:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name'
cannot be null 500 Internal Server Error - DBALException
It's seems a problem calling $tag = parent::createTag($name); in line35 of TagManager.php
Any ideas?
v.
I came across the same issue in my project.
The problem was that the Tag entity prevented the execution of the constructor in the BaseTag (FPN\TagBundle\Entity\Tag) class. I am pretty sure that your Tag class has its own constructor and you do not call the parent one, which sets the name attribute missing in your entity.
Here is an example custom Tag class which calls the parent constructor to set the name:
use FPN\TagBundle\Entity\Tag as BaseTag;
class Tag extends BaseTag
{
protected $tagging;
public function __construct($name = null)
{
parent::__construct($name);
$this->tagging = new ArrayCollection();
}
}
following is an excerpt from my entity class
public class PartyRole implements Serializable {
#Id
#GeneratedValue(generator = "IDGenerator", strategy = SEQUENCE)
#SequenceGenerator(name = "IDGenerator", sequenceName = "IDGenerator", allocationSize = 1)
private long id;
I am working in Eclipse and I am using Derby 10.8.2.2
I have created a Sequence
CREATE SEQUENCE IDGenerator AS BIGINT START WITH 1 INCREMENT BY 1;
following is the code in my main method.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("notesJPA");
EntityManager entityManager = factory.createEntityManager();
EntityTransaction tx = entityManager.getTransaction();
tx.begin();
entityManager.persist(actor);
//entityManager.persist(director);
//entityManager.persist(castingManager);
//entityManager.persist(producer);
//entityManager.persist(screenWriter);
//entityManager.persist(storyWriter);
tx.commit();
When I comment out all calls to persist method except the first, things work fine.
When I uncomment the lines, I get the following error.
[EL Warning]: 2012-03-07 18:57:03.098--UnitOfWork(2079310344)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL120307183732430' defined on 'PARTYROLE'.
Error Code: -1
Call: INSERT INTO PARTYROLE (ID, NAME, DTYPE) VALUES (?, ?, ?)
bind => [0, CastingManager, CastingManager]
Query: InsertObjectQuery(com.ats.data.partyrole.CastingManager#72f6f1b6)
Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL120307183732430' defined on 'PARTYROLE'.
Error Code: -1
Call: INSERT INTO PARTYROLE (ID, NAME, DTYPE) VALUES (?, ?, ?)
bind => [0, CastingManager, CastingManager]
Query: InsertObjectQuery(com.ats.data.partyrole.CastingManager#72f6f1b6)
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 amrite.com.jpa.test.LoadPartyRoles.main(LoadPartyRoles.java:38)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL120307183732430' defined on 'PARTYROLE'.
Error Code: -1
Call: INSERT INTO PARTYROLE (ID, NAME, DTYPE) VALUES (?, ?, ?)
bind => [0, CastingManager, CastingManager]
Query: InsertObjectQuery(com.ats.data.partyrole.CastingManager#72f6f1b6)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:801)
Why am I getting this error? I think I have done all the right things.
For some reason the JPA provider (EclipseLink) is not picking up the next id from the Sequence. Is this a bug? or something I am doing wrong?