`InvalidQueryException: cannot parse '[B#50908fa9' as hex bytes` using Datastax Java driver - java

I am trying to insert byte array into Blob data type in my Cassandra table.. I am using Datastax Java driver. Below is my code -
for (Map.Entry<String, byte[]> entry : attributes.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
String cql = "insert into test_data (user_id, name, value) values ('"+userId+"', '"+entry.getKey()+"', '"+entry.getValue()+"');";
System.out.println(cql);
CassandraDatastaxConnection.getInstance();
CassandraDatastaxConnection.getSession().execute(cql);
}
And this is the exception I am getting back -
InvalidQueryException: cannot parse '[B#50908fa9' as hex bytes
I guess the problem is, the way I am making my above cql.. Something is missing for sure...
I have created the table like this -
create table test_data (user_id text, name text, value blob, primary key (user_id, name));
Can anybody help me? Thanks...

The problem is that when you append the byte array to the String it calls toString on the byte[] which prints the unhelpful pointer you are seeing. You need to manually convert it to a String for your data type. In your case you are using a blob, so you need to convert to a hex string.
This question has code for converting the byte[] to String:
How to convert a byte array to a hex string in Java?
You can use one of those functions and prepend '0x' to it. Then you should have a valid String for your blob.

Related

Recompute Key from another variable Key and static Key?

I'm looking a way to do something like this. I don't know how to call it, so i don't know if it exist or how to find it. Some keyword would be welcome :)
String var_1 = "user data";
String fix_1 = "supply data";
String mix = mixer(var_1,fix_1);
// mix = " something fully random "
String var_2 = "user data changed";
String fix_2 = fixer(var_2,mix);
And mix == mixer(var_2, fix_2);
So to resume, I need to generate a random data from 2 variables. 1 is variable from user and 1 is supply by me.
First time , I generate the data with these 2 variables with one function.
Then, if the user data change, with another function, I compute the new supply data with the first result and the new user data. And if I use again the computed data and the new user data, I must obtain the same data computed the first time.
Is there something to do that ? Like some cipher technique or so?
Thanks for Intel.
In fact there is something like this already which may satisfy you needs. In fact you know this function too. It's the good old XOR. And yes, it is used in crypto a lot. In fact it's the core idea of the stream ciphers and the One Time Pad.
It goes like this:
Assume you have a byte array of length n called var_1.
Assume you have a random value fix_1 of the same length.
If you do var_1 XOR fix_1 you get mix.
If you do mix XOR fix_1 you get var_1 again. (Basic math: fix_1 XOR fix_1 equals chain of zero value bytes and var_1 XOR zero bytes = var_1.
This whole thing will be as random and secure as random and secret fix_1 remains. If one of the values is not random the approach is not secure at all.
So following the idea of User253751 in comment, I was able to do it.
Step:
generate the private constant key => privateKey = encrypt(publicKey, Password_1) (the first public key is random )
if password change, generate a new public key by decoding the private constant key with password_2 => publicKey_Updated = decrypt(privateKey, Password_2)
Check if the new public key is valid : privateKey_Rebuild = encrypt(publicKey_Updated, Password_2) ====> if everything is ok, privateKey == privateKey_Rebuild.
---> I test it only with a low cryptage i use just for obfuscation, but it should work with symmetric key too. I'm not sur about Asymetric key, because to make this work, you need a crypting protocol who always give you the same crypted data with the same input. And RSA do not gave you the same crypted data even with the same input.
Here my code (not a copy/paste snippet beacause it use my own library), but you can catch the idea easily with the function name.
KeyObfusc publicKey_1 = KeyObfusc.fromPassword("publicKey_1");
KeyObfusc password_1 = KeyObfusc.fromPassword("password_1");
Encoder encoder_1 = new Encoder(password_1, CipherFormat.HEX);
Decoder decoder_1 = new Decoder(password_1, CipherFormat.HEX);
byte[] privateKey = encoder_1.toBytes(publicKey_1.getEncoded());
byte[] publicKey_1_Rebuild = decoder_1.fromBytesToBytes(privateKey);
LogDelay.send("password_1 : " + BytesTo.stringHex(password_1.getEncoded()));
LogDelay.send("publicKey_1 : " + BytesTo.stringHex(publicKey_1.getEncoded()));
LogDelay.send("privateKey : " + BytesTo.stringHex(privateKey));
LogDelay.send("publicKey_1 Rebuild : " + Arrays.equals(publicKey_1.getEncoded(), publicKey_1_Rebuild) +
" " + BytesTo.stringHex(publicKey_1_Rebuild));
LogDelay.send();
KeyObfusc password_2 = KeyObfusc.fromPassword("password_2");
Encoder encoder_2 = new Encoder(password_2, CipherFormat.HEX);
Decoder decoder_2 = new Decoder(password_2, CipherFormat.HEX);
byte[] publicKey_2 = decoder_2.fromBytesToBytes(privateKey);
byte[] privateKey_Rebuild = encoder_2.toBytes(publicKey_2);
LogDelay.send("password_2 : " + BytesTo.stringHex(password_2.getEncoded()));
LogDelay.send("publicKey_2 : " + BytesTo.stringHex(publicKey_2));
LogDelay.send("privateKey Rebuild: " + Arrays.equals(privateKey, privateKey_Rebuild) +
" " + BytesTo.stringHex(privateKey_Rebuild));
LogDelay.send();

My Customer data is being truncated when added to my List [duplicate]

I am running data.bat file with the following lines:
Rem Tis batch file will populate tables
cd\program files\Microsoft SQL Server\MSSQL
osql -U sa -P Password -d MyBusiness -i c:\data.sql
The contents of the data.sql file is:
insert Customers
(CustomerID, CompanyName, Phone)
Values('101','Southwinds','19126602729')
There are 8 more similar lines for adding records.
When I run this with start > run > cmd > c:\data.bat, I get this error message:
1>2>3>4>5>....<1 row affected>
Msg 8152, Level 16, State 4, Server SP1001, Line 1
string or binary data would be truncated.
<1 row affected>
<1 row affected>
<1 row affected>
<1 row affected>
<1 row affected>
<1 row affected>
Also, I am a newbie obviously, but what do Level #, and state # mean, and how do I look up error messages such as the one above: 8152?
From #gmmastros's answer
Whenever you see the message....
string or binary data would be truncated
Think to yourself... The field is NOT big enough to hold my data.
Check the table structure for the customers table. I think you'll find that the length of one or more fields is NOT big enough to hold the data you are trying to insert. For example, if the Phone field is a varchar(8) field, and you try to put 11 characters in to it, you will get this error.
I had this issue although data length was shorter than the field length.
It turned out that the problem was having another log table (for audit trail), filled by a trigger on the main table, where the column size also had to be changed.
In one of the INSERT statements you are attempting to insert a too long string into a string (varchar or nvarchar) column.
If it's not obvious which INSERT is the offender by a mere look at the script, you could count the <1 row affected> lines that occur before the error message. The obtained number plus one gives you the statement number. In your case it seems to be the second INSERT that produces the error.
Just want to contribute with additional information: I had the same issue and it was because of the field wasn't big enough for the incoming data and this thread helped me to solve it (the top answer clarifies it all).
BUT it is very important to know what are the possible reasons that may cause it.
In my case i was creating the table with a field like this:
Select '' as Period, * From Transactions Into #NewTable
Therefore the field "Period" had a length of Zero and causing the Insert operations to fail. I changed it to "XXXXXX" that is the length of the incoming data and it now worked properly (because field now had a lentgh of 6).
I hope this help anyone with same issue :)
Some of your data cannot fit into your database column (small). It is not easy to find what is wrong. If you use C# and Linq2Sql, you can list the field which would be truncated:
First create helper class:
public class SqlTruncationExceptionWithDetails : ArgumentOutOfRangeException
{
public SqlTruncationExceptionWithDetails(System.Data.SqlClient.SqlException inner, DataContext context)
: base(inner.Message + " " + GetSqlTruncationExceptionWithDetailsString(context))
{
}
/// <summary>
/// PArt of code from following link
/// http://stackoverflow.com/questions/3666954/string-or-binary-data-would-be-truncated-linq-exception-cant-find-which-fiel
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
static string GetSqlTruncationExceptionWithDetailsString(DataContext context)
{
StringBuilder sb = new StringBuilder();
foreach (object update in context.GetChangeSet().Updates)
{
FindLongStrings(update, sb);
}
foreach (object insert in context.GetChangeSet().Inserts)
{
FindLongStrings(insert, sb);
}
return sb.ToString();
}
public static void FindLongStrings(object testObject, StringBuilder sb)
{
foreach (var propInfo in testObject.GetType().GetProperties())
{
foreach (System.Data.Linq.Mapping.ColumnAttribute attribute in propInfo.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), true))
{
if (attribute.DbType.ToLower().Contains("varchar"))
{
string dbType = attribute.DbType.ToLower();
int numberStartIndex = dbType.IndexOf("varchar(") + 8;
int numberEndIndex = dbType.IndexOf(")", numberStartIndex);
string lengthString = dbType.Substring(numberStartIndex, (numberEndIndex - numberStartIndex));
int maxLength = 0;
int.TryParse(lengthString, out maxLength);
string currentValue = (string)propInfo.GetValue(testObject, null);
if (!string.IsNullOrEmpty(currentValue) && maxLength != 0 && currentValue.Length > maxLength)
{
//string is too long
sb.AppendLine(testObject.GetType().Name + "." + propInfo.Name + " " + currentValue + " Max: " + maxLength);
}
}
}
}
}
}
Then prepare the wrapper for SubmitChanges:
public static class DataContextExtensions
{
public static void SubmitChangesWithDetailException(this DataContext dataContext)
{
//http://stackoverflow.com/questions/3666954/string-or-binary-data-would-be-truncated-linq-exception-cant-find-which-fiel
try
{
//this can failed on data truncation
dataContext.SubmitChanges();
}
catch (SqlException sqlException) //when (sqlException.Message == "String or binary data would be truncated.")
{
if (sqlException.Message == "String or binary data would be truncated.") //only for EN windows - if you are running different window language, invoke the sqlException.getMessage on thread with EN culture
throw new SqlTruncationExceptionWithDetails(sqlException, dataContext);
else
throw;
}
}
}
Prepare global exception handler and log truncation details:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
string message = ex.Message;
//TODO - log to file
}
Finally use the code:
Datamodel.SubmitChangesWithDetailException();
Another situation in which you can get this error is the following:
I had the same error and the reason was that in an INSERT statement that received data from an UNION, the order of the columns was different from the original table. If you change the order in #table3 to a, b, c, you will fix the error.
select a, b, c into #table1
from #table0
insert into #table1
select a, b, c from #table2
union
select a, c, b from #table3
on sql server you can use SET ANSI_WARNINGS OFF like this:
using (SqlConnection conn = new SqlConnection("Data Source=XRAYGOAT\\SQLEXPRESS;Initial Catalog='Healthy Care';Integrated Security=True"))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
try
{
using cmd = new SqlCommand("", conn, trans))
{
cmd.CommandText = "SET ANSI_WARNINGS OFF";
cmd.ExecuteNonQuery();
cmd.CommandText = "YOUR INSERT HERE";
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "SET ANSI_WARNINGS ON";
cmd.ExecuteNonQuery();
trans.Commit();
}
}
catch (Exception)
{
trans.Rollback();
}
}
conn.Close();
}
I had the same issue. The length of my column was too short.
What you can do is either increase the length or shorten the text you want to put in the database.
Also had this problem occurring on the web application surface.
Eventually found out that the same error message comes from the SQL update statement in the specific table.
Finally then figured out that the column definition in the relating history table(s) did not map the original table column length of nvarchar types in some specific cases.
I had the same problem, even after increasing the size of the problematic columns in the table.
tl;dr: The length of the matching columns in corresponding Table Types may also need to be increased.
In my case, the error was coming from the Data Export service in Microsoft Dynamics CRM, which allows CRM data to be synced to an SQL Server DB or Azure SQL DB.
After a lengthy investigation, I concluded that the Data Export service must be using Table-Valued Parameters:
You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.
As you can see in the documentation above, Table Types are used to create the data ingestion procedure:
CREATE TYPE LocationTableType AS TABLE (...);
CREATE PROCEDURE dbo.usp_InsertProductionLocation
#TVP LocationTableType READONLY
Unfortunately, there is no way to alter a Table Type, so it has to be dropped & recreated entirely. Since my table has over 300 fields (😱), I created a query to facilitate the creation of the corresponding Table Type based on the table's columns definition (just replace [table_name] with your table's name):
SELECT 'CREATE TYPE [table_name]Type AS TABLE (' + STRING_AGG(CAST(field AS VARCHAR(max)), ',' + CHAR(10)) + ');' AS create_type
FROM (
SELECT TOP 5000 COLUMN_NAME + ' ' + DATA_TYPE
+ IIF(CHARACTER_MAXIMUM_LENGTH IS NULL, '', CONCAT('(', IIF(CHARACTER_MAXIMUM_LENGTH = -1, 'max', CONCAT(CHARACTER_MAXIMUM_LENGTH,'')), ')'))
+ IIF(DATA_TYPE = 'decimal', CONCAT('(', NUMERIC_PRECISION, ',', NUMERIC_SCALE, ')'), '')
AS field
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '[table_name]'
ORDER BY ORDINAL_POSITION) AS T;
After updating the Table Type, the Data Export service started functioning properly once again! :)
When I tried to execute my stored procedure I had the same problem because the size of the column that I need to add some data is shorter than the data I want to add.
You can increase the size of the column data type or reduce the length of your data.
A 2016/2017 update will show you the bad value and column.
A new trace flag will swap the old error for a new 2628 error and will print out the column and offending value. Traceflag 460 is available in the latest cumulative update for 2016 and 2017:
https://support.microsoft.com/en-sg/help/4468101/optional-replacement-for-string-or-binary-data-would-be-truncated
Just make sure that after you've installed the CU that you enable the trace flag, either globally/permanently on the server:
...or with DBCC TRACEON:
https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-traceon-trace-flags-transact-sql?view=sql-server-ver15
Another situation, in which this error may occur is in
SQL Server Management Studio. If you have "text" or "ntext" fields in your table,
no matter what kind of field you are updating (for example bit or integer).
Seems that the Studio does not load entire "ntext" fields and also updates ALL fields instead of the modified one.
To solve the problem, exclude "text" or "ntext" fields from the query in Management Studio
This Error Comes only When any of your field length is greater than the field length specified in sql server database table structure.
To overcome this issue you have to reduce the length of the field Value .
Or to increase the length of database table field .
If someone is encountering this error in a C# application, I have created a simple way of finding offending fields by:
Getting the column width of all the columns of a table where we're trying to make this insert/ update. (I'm getting this info directly from the database.)
Comparing the column widths to the width of the values we're trying to insert/ update.
Assumptions/ Limitations:
The column names of the table in the database match with the C# entity fields. For eg: If you have a column like this in database:
You need to have your Entity with the same column name:
public class SomeTable
{
// Other fields
public string SourceData { get; set; }
}
You're inserting/ updating 1 entity at a time. It'll be clearer in the demo code below. (If you're doing bulk inserts/ updates, you might want to either modify it or use some other solution.)
Step 1:
Get the column width of all the columns directly from the database:
// For this, I took help from Microsoft docs website:
// https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.getschema?view=netframework-4.7.2#System_Data_SqlClient_SqlConnection_GetSchema_System_String_System_String___
private static Dictionary<string, int> GetColumnSizesOfTableFromDatabase(string tableName, string connectionString)
{
var columnSizes = new Dictionary<string, int>();
using (var connection = new SqlConnection(connectionString))
{
// Connect to the database then retrieve the schema information.
connection.Open();
// You can specify the Catalog, Schema, Table Name, Column Name to get the specified column(s).
// You can use four restrictions for Column, so you should create a 4 members array.
String[] columnRestrictions = new String[4];
// For the array, 0-member represents Catalog; 1-member represents Schema;
// 2-member represents Table Name; 3-member represents Column Name.
// Now we specify the Table_Name and Column_Name of the columns what we want to get schema information.
columnRestrictions[2] = tableName;
DataTable allColumnsSchemaTable = connection.GetSchema("Columns", columnRestrictions);
foreach (DataRow row in allColumnsSchemaTable.Rows)
{
var columnName = row.Field<string>("COLUMN_NAME");
//var dataType = row.Field<string>("DATA_TYPE");
var characterMaxLength = row.Field<int?>("CHARACTER_MAXIMUM_LENGTH");
// I'm only capturing columns whose Datatype is "varchar" or "char", i.e. their CHARACTER_MAXIMUM_LENGTH won't be null.
if(characterMaxLength != null)
{
columnSizes.Add(columnName, characterMaxLength.Value);
}
}
connection.Close();
}
return columnSizes;
}
Step 2:
Compare the column widths with the width of the values we're trying to insert/ update:
public static Dictionary<string, string> FindLongBinaryOrStringFields<T>(T entity, string connectionString)
{
var tableName = typeof(T).Name;
Dictionary<string, string> longFields = new Dictionary<string, string>();
var objectProperties = GetProperties(entity);
//var fieldNames = objectProperties.Select(p => p.Name).ToList();
var actualDatabaseColumnSizes = GetColumnSizesOfTableFromDatabase(tableName, connectionString);
foreach (var dbColumn in actualDatabaseColumnSizes)
{
var maxLengthOfThisColumn = dbColumn.Value;
var currentValueOfThisField = objectProperties.Where(f => f.Name == dbColumn.Key).First()?.GetValue(entity, null)?.ToString();
if (!string.IsNullOrEmpty(currentValueOfThisField) && currentValueOfThisField.Length > maxLengthOfThisColumn)
{
longFields.Add(dbColumn.Key, $"'{dbColumn.Key}' column cannot take the value of '{currentValueOfThisField}' because the max length it can take is {maxLengthOfThisColumn}.");
}
}
return longFields;
}
public static List<PropertyInfo> GetProperties<T>(T entity)
{
//The DeclaredOnly flag makes sure you only get properties of the object, not from the classes it derives from.
var properties = entity.GetType()
.GetProperties(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.DeclaredOnly)
.ToList();
return properties;
}
Demo:
Let's say we're trying to insert someTableEntity of SomeTable class that is modeled in our app like so:
public class SomeTable
{
[Key]
public long TicketID { get; set; }
public string SourceData { get; set; }
}
And it's inside our SomeDbContext like so:
public class SomeDbContext : DbContext
{
public DbSet<SomeTable> SomeTables { get; set; }
}
This table in Db has SourceData field as varchar(16) like so:
Now we'll try to insert value that is longer than 16 characters into this field and capture this information:
public void SaveSomeTableEntity()
{
var connectionString = "server=SERVER_NAME;database=DB_NAME;User ID=SOME_ID;Password=SOME_PASSWORD;Connection Timeout=200";
using (var context = new SomeDbContext(connectionString))
{
var someTableEntity = new SomeTable()
{
SourceData = "Blah-Blah-Blah-Blah-Blah-Blah"
};
context.SomeTables.Add(someTableEntity);
try
{
context.SaveChanges();
}
catch (Exception ex)
{
if (ex.GetBaseException().Message == "String or binary data would be truncated.\r\nThe statement has been terminated.")
{
var badFieldsReport = "";
List<string> badFields = new List<string>();
// YOU GOT YOUR FIELDS RIGHT HERE:
var longFields = FindLongBinaryOrStringFields(someTableEntity, connectionString);
foreach (var longField in longFields)
{
badFields.Add(longField.Key);
badFieldsReport += longField.Value + "\n";
}
}
else
throw;
}
}
}
The badFieldsReport will have this value:
'SourceData' column cannot take the value of
'Blah-Blah-Blah-Blah-Blah-Blah' because the max length it can take is
16.
Kevin Pope's comment under the accepted answer was what I needed.
The problem, in my case, was that I had triggers defined on my table that would insert update/insert transactions into an audit table, but the audit table had a data type mismatch where a column with VARCHAR(MAX) in the original table was stored as VARCHAR(1) in the audit table, so my triggers were failing when I would insert anything greater than VARCHAR(1) in the original table column and I would get this error message.
I used a different tactic, fields that are allocated 8K in some places. Here only about 50/100 are used.
declare #NVPN_list as table
nvpn varchar(50)
,nvpn_revision varchar(5)
,nvpn_iteration INT
,mpn_lifecycle varchar(30)
,mfr varchar(100)
,mpn varchar(50)
,mpn_revision varchar(5)
,mpn_iteration INT
-- ...
) INSERT INTO #NVPN_LIST
SELECT left(nvpn ,50) as nvpn
,left(nvpn_revision ,10) as nvpn_revision
,nvpn_iteration
,left(mpn_lifecycle ,30)
,left(mfr ,100)
,left(mpn ,50)
,left(mpn_revision ,5)
,mpn_iteration
,left(mfr_order_num ,50)
FROM [DASHBOARD].[dbo].[mpnAttributes] (NOLOCK) mpna
I wanted speed, since I have 1M total records, and load 28K of them.
This error may be due to less field size than your entered data.
For e.g. if you have data type nvarchar(7) and if your value is 'aaaaddddf' then error is shown as:
string or binary data would be truncated
You simply can't beat SQL Server on this.
You can insert into a new table like this:
select foo, bar
into tmp_new_table_to_dispose_later
from my_table
and compare the table definition with the real table you want to insert the data into.
Sometime it's helpful sometimes it's not.
If you try inserting in the final/real table from that temporary table it may just work (due to data conversion working differently than SSMS for example).
Another alternative is to insert the data in chunks, instead of inserting everything immediately you insert with top 1000 and you repeat the process, till you find a chunk with an error. At least you have better visibility on what's not fitting into the table.

How Convert Microsoft GUID to JAVA UUID?

I need to communicate a Guid that was generated in .NET to a Java application.
This is my GUID
ce095552-b466-4d03-ac41-430ec9286806
and I want to set it to UUID variable !
UUID.nameUUIDFromBytes(stringUUID.getBytes())
UUID.fromString(stringUUID)
I am getting error
Caused by: java.lang.NumberFormatException: Invalid long: ""ce095552"
how can I cast GUID to UUID?
When you get some Microsoft objectGUIDs , Active Directory objectGUID of the group object for example, you need to get the binary and then convert it to hexadecimal after then you need generate a MS GUID (look at order byte sequence inside convertToDashedString function).
The byte order comparing UUID and GUID is different: try convert it using online converters like: robobunny converter
Now I'm storing and working with ms guid
public static String convertMSGUIDToHexFormat(String guid){
guid = guid.replaceAll("-", "");
guid = guid.replaceAll("(.{8})(.{4})(.{4})(.{4})(.{12})", "$1-$2-$3-$4-$5").replaceAll("(.{2})(.{2})(.{2})(.{2}).(.{2})(.{2}).(.{2})(.{2})(.{18})", "$4$3$2$1-$6$5-$8$7$9");
guid = guid.replaceAll("-", "");
return guid;
}
public static String convertHexToMSGUIDFormat(String hex){
return hex.replaceAll("(.{8})(.{4})(.{4})(.{4})(.{12})", "$1-$2-$3-$4-$5").replaceAll("(.{2})(.{2})(.{2})(.{2}).(.{2})(.{2}).(.{2})(.{2})(.{18})", "$4$3$2$1-$6$5-$8$7$9");
}
When I know a better way, then I change that supposed quick fix
UUID.fromString() works fine:
String guid = "ce095552-b466-4d03-ac41-430ec9286806";
UUID uuid = UUID.fromString(guid);
System.out.println(uuid);
Invalid long: ""ce095552"
Looks like the GUID you are passing to UUID.fromString still includes quotes ("). Make sure the GUID string does not include any additional characters and it should work.
String guid = "41e72bd6-d38f-4f78-855f-160562262a54";
UUID uuid = UUID.fromString(guid);
ReadValueId readValueId = new ReadValueId(
new NodeId(2, uuid),
AttributeId.Value.uid(), null, QualifiedName.NULL_VALUE);

How to save a UUID as binary(16) in java

I have a table TestTable with columns ID as binary(16) and name as varchar(50)
I've been trying to store an ordered UUID as PK like in this article Store UUID in an optimized way
I see the UUID is saved in database as HEX (blob)
So I want to save this ID from java but I am getting this error
Data truncation: Data too long for column 'ID' at row 1
I am currently using the library sql2o to interact with mysql
So basically this is my code
String suuid = UUID.randomUUID().toString();
String partial_id = suuid.substring(14,18) + suuid.substring(9, 13) + suuid.substring(0, 8) + suuid.substring(19, 23) + suuid.substring(24)
String final_id = String.format("%040x", new BigInteger(1, partial_id.getBytes()));
con.createQuery("INSERT INTO TestTable(ID, Name) VALUES(:id, :name)")
.addParameter("id", final_id)
.addParameter("name", "test1").executeUpdate();
The partial id should be something like this 11d8eebc58e0a7d796690800200c9a66
I tried this statement in mysql without issue
insert into testtable(id, name) values(UNHEX(CONCAT(SUBSTR(uuid(), 15, 4),SUBSTR(uuid(), 10, 4),SUBSTR(uuid(), 1, 8),SUBSTR(uuid(), 20, 4),SUBSTR(uuid(), 25))), 'Test2');
But I got the same error when I remove the unhex function. So how can I send the correct ID from Java to mysql?
UPDATE
I solved my problem inspired on the answer of David Ehrmann. But in my case I used the HexUtils from tomcat to transform my sorted UUID string into bytes[]:
byte[] final_id = HexUtils.fromHexString(partial_id);
Try storing it as bytes:
UUID uuid = UUID.randomUUID();
byte[] uuidBytes = new byte[16];
ByteBuffer.wrap(uuidBytes)
.order(ByteOrder.BIG_ENDIAN)
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits());
con.createQuery("INSERT INTO TestTable(ID, Name) VALUES(:id, :name)")
.addParameter("id", uuidBytes)
.addParameter("name", "test1").executeUpdate();
A bit of an explanation: your table is using BINARY(16), so serializing UUID as its raw bytes is a really straightforward approach. UUIDs are essentially 128-bit ints with a few reserved bits, so this code writes it out as a big-endian 128-bit int. The ByteBuffer is just an easy way to turn two longs into a byte array.
Now in practice, all the conversion effort and headaches won't be worth the 20 bytes you save per row.

Hazelcast not able to read data into my own class object using IMap.get, where data inserted using Memcached text protocol

I am inserting record into Hazelcast from C Application using Memcached Client Library API's, where record is as follows:
typedef struct _activeClient
{
char ID[25];
int IP;
char aMethod[16];
}activeClient;
Now I am trying reading same record using Hazelcast Java Native API's. Here is my Java program.
IMap < String, MemcacheEntry > mapInst = client.getMap("hz_memcache_ABC_MAP");
System.out.println("Map Size:" + mapInst.size());
String key = new String("70826892122991");
MemcacheEntry tmpValRec = pvrMapIst.get(key);
System.out.println("Key:" + key + "ID:" + tmpValRec.getValue());
Here tmpValRec.getValue() printing record content in single String format. But, I want to retrive each member value from tmpValRec to my own java class object. Here is the class
class ActiveClients
{
String ueID;
int Ip;
String aMethod;
ActiveClients()
{
ueID = "";
Ip = 0;
aMethod = "";
}
}
Pointing me to an example would be great help.
I guess the only option is to parse the string to deserialize your object. I know this is a pain, but I don't see a better alternative. Unless of course you store a blob as a value in memcached where the blob is the serialized content of the class.

Categories