MySql Java separating identical errors thrown - java

I am dealing with insert statements into a database on Mysql. I have a users table where I have a unique key on the username and on the email. This way I can get an SQLIntegrityConstraintViolationException when I try inserting a new user into the database. The problem is if both the username and email throw the same exception if there are duplicate entries, how can I tell which one is throwing the exception.
The end goal I want to tell the user whether that username is already taken.. or if that username is already registered.
Thanks,

Usually the exception message contains the object name of the violated constraint. Whenever an SQLIntegrityConstraintViolationException is thrown, you can check which constraint name is within the exception message and set display message based on that.

Related

org.hibernate.HibernateException: Missing table exception though MySQL table is present

I am connecting to a MySQL table using JPA Hibernate. But I am getting error in my Java code:
org.hibernate.HibernateException: Missing table
My table is present in MySQL database schema. I am not getting why missing table exception is thrown here. This is a newly created table. All other existing tables in the same schema are accessible from Hibernate. I saw similar posts with same error. But the answers there didn't help my cause. Can you please let me know what can be the issue here.
If table is present, then most likely it is user permission issue. This happens if you have created the table using a different MySQL user. Make sure the MySQL username/password that you are using in Hibernate is having access to the table. To test, login to MySQL console directly using Hibernate credential & run a select query on the table. If you see similar error as below, then you need to grant access to the table for the Hibernate user.
ERROR 1142 (42000): SELECT command denied to user
Source: http://www.w3spot.com/2020/10/how-to-solve-caused-by-hibernateexception-missing-table.html
Make sure the user has access to the table
Make sure names are equals in terms of case sensitivity
Make sure the schema name and table name are not misspelled
If you share more information about the issue, it would be easier to pinpoint the problem.
Chances are there is an inheritance scenario with a physical table that you assumed to be abstract.
To dig deeper you can put a breakpoint in org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl#getTablesInformation which calls extractor.getTable to see why your table is not returned as part of schema tables.
Rerun the app with the specified breakpoint and step through lines to get to the line which queries table names from the database metadat.
#Override
public TableInformation getTableInformation(QualifiedTableName tableName) {
if ( tableName.getObjectName() == null ) {
throw new IllegalArgumentException( "Passed table name cannot be null" );
}
return extractor.getTable(
tableName.getCatalogName(),
tableName.getSchemaName(),
tableName.getTableName()
);
}

How do I get field name from unique constraint exception in JPA

I understand that if I try to insert a record using JPA and if it violates unique constrain, it throws an exception which contains cause MySQLIntegrityConstraintViolationException.
I want to show user friendly message to the user. So I would like to get the field name for which violation occured. I can get the message using cause which gives message something like Duplicate entry '1' for key 'DOCUMENT_NUMBER'.
But I feel relying on message(e.getCause().getCause().getMessage()) is not a good idea.
The entity may contain several other unique constraints like emailid, vat number etc.
So I would like to get the field name for which constraint violation occured.
Could some one please help how to get the field name?
Thanks in advance,
Kitty
you can try below code
try{
//here your code
...
}catch (ConstraintViolationException e) {
for(ConstraintViolation violation : e.getConstraintViolations()) {
System.out.println(violation.getMessage());
}
}
Also for detail explanation of ConstraintViolationException see Java doc.

Handling Hibernate's error codes?

Consider an hypothetical User table:
-- postgres, but it could have been any other SQL database
CREATE TABLE User(
id SERIAL PRIMARY KEY,
mail VARCHAR(32) UNIQUE NOT NULL
);
Let's assume I attempt to add two users with the same mail:
session.save(new User(1, "xpto#gmail.com"));
session.save(new User(2, "xpto#gmail.com"));
and execute it through Hibernate. Hibernate will throw me an ConstraintViolationException:
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
...
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "users_mail_key"
Detail: Key (mail)=(xpto#gmail.com) already exists.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
...
What I'd like to know is if there's some good way, other than having to manually parse the Exception's output text, to gather what is the reason of the error so I may correctly interpret and react to the problem.
I realize that this may actually be more of a Postgres Driver's problem than actually an Hibernate one, but I'm unsure at this stage so I thought it may opportune to ask in Hibernate's context.
So if you are able to get a value from getSQLState, you can handle the exception:
"All messages emitted by the PostgreSQL server are assigned five-character error codes that follow the SQL standard's conventions for "SQLSTATE" codes. Applications that need to know which error condition has occurred should usually test the error code, rather than looking at the textual error message."
From: http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html
23505 = unique_violation
Note: In this link there is also the list.
Well, after looking at Postgres Driver's source code it seems the problem lies with Postgres and not with Hibernate. PSQLException will contain some information, although it certainly isn't as polished as I first assumed :(
} catch (PSQLException e) {
ServerErrorMessage m = e.getServerErrorMessage();
System.out.println(m.getColumn());
System.out.println(m.getConstraint());
System.out.println(m.getDatatype());
System.out.println(m.getDetail());
System.out.println(m.getFile());
System.out.println(m.getHint());
System.out.println(m.getInternalPosition());
System.out.println(m.getInternalQuery());
System.out.println(m.getLine());
System.out.println(m.getMessage());
System.out.println(m.getPosition());
System.out.println(m.getRoutine());
System.out.println(m.getSchema());
System.out.println(m.getSeverity());
System.out.println(m.getSQLState());
System.out.println(m.getTable());
System.out.println(m.getWhere());
}
prints
null
users_mail_key
null
Key (mail)=(xpto#gmail.com) already exists.
nbtinsert.c
null
0
null
398
duplicate key value violates unique constraint "users_mail_key"
0
_bt_check_unique
public
ERROR
23505
users
null

How to compare SQLite Column against a user string?

I am creating a JFrameApplet (In Java) with a log in (SQLite) but I am struggling to understand how to compare a wanted username, against a username that is already taken:
For Example: I want the username JoeBloggs, but it is taken, how do I compare a wanted username against one already made.
I have an SQLite users.db and the field is USERNAME.
Thank you for any assistance.
Try searching up the UNIQUE constraint.
When creating a table useCREATE TABLE Users(Id INTEGER, USERNAME TEXT UNIQUE);
so if JoeBloggs is already an entry in the db trying to add it again with INSERT INTO Users VALUES(2, 'JoeBloggs'); will give you an Error: column USERNAME is not unique.

How to force treat MySQL Constraint Errors from Hibernate

I have a Java Web Project that uses Hibernate and MySQL. I have trouble to treat exceptions like when i try to insert a new register at database with the same primary key (Intentionally)
i got the following error with a message box "Could not insert:...". But i don't want to shows directly to user this error, i want to treat when i call "Persisten.save()", but in my code it doesn't appears nothing wrong (for my ide, i threat all possible excepetions).
So how can i change (configuration/code) to force threat exceptions like that and change the message?!
You should check if the Id already exists in the database before you try to persist it.

Categories