How to check if UUID is null, empty or blank? - spring-boot

I have a Springboot application and my entity have a field id and ownerId which is type of UUID.
How can i check if the UUID is actually a UUID and not a string or anything else?
My example code:
when {
project.id != null -> handleIllegalParameter("id")
project.ownerId != null -> handleIllegalParameter("ownerId")
project.name.isNullOrBlank() -> handleMissingRequiredField("name")
}
How can I can check that is actually a UUID and not a string, integer or anything else except UUID?

If your id and ownerId are of type UUID? then once you check they are not null - you are good. If they of type String (as the title of your question implies) you can use the UUID.fromString() method that throws IllegalArgumentException if the conversion fails.

Related

Gorm Find() query not populating all fields defined in the defined struct holding the result set

The problem that I've is tx returned in result set doesn't have all fields set. Not able to figure out why? It has value in the actual database table.
// request object supplied in FetchTransactionWithHighestExpiry:
type ProvisionRequest struct {
Identity string `json:"identity"`
IdentityType string `json:"identityType"`
}
// struct to model database table
type Transactions struct {
Identity string `gorm:"index;not null"`
IdentityType string
}
// method where there is problem
func (c *DBClient) FetchTransactionWithHighestExpiry(req *model.ProvisionRequest) (model.Transactions, error) {
var tx model.Transactions
res := c.client.Model(&model.Transactions{}).Where("identity = ? AND endDate > ?", req.Identity, time.Now().Unix()).Order("endDate desc").First(&tx)
return tx, res.Error
}
My tx has only value of identity set whereas identityType is an empty string. Any ideas what i'm doing wrong here?
Edit 1: transactions table schema
-- rp.transactions definition
CREATE TABLE `transactions` (
`transaction_id` varchar(255) NOT NULL,
`identity` varchar(255) DEFAULT NULL,
`identityType` varchar(15) DEFAULT NULL,
`serviceId` varchar(255) DEFAULT NULL,
`partnerId` varchar(255) DEFAULT NULL,
`countryId` varchar(255) DEFAULT NULL,
`updatedAt` timestamp NULL DEFAULT NULL,
`createdAt` timestamp NULL DEFAULT NULL,
`startDate` int NOT NULL,
`endDate` int NOT NULL,
PRIMARY KEY (`transaction_id`),
KEY `identity_idx` (`identity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
By default, when constructing a query, gorm will use snake_case convention to convert Identity and IdentityType fields to identity and identity_type columns.
If your table columns are named differently, you need to specify this.
// struct to model database table
type Transactions struct {
Identity string `gorm:"index;not null"`
IdentityType string `gorm:"column:identityType"`
}

Dealing with nullable UUID in a controller - SpringBoot and Postgres

I have an entity that includes a nullable UUID (but it is not an ID), as follows:
#Column(nullable = true)
var myField: UUID? = null
I also have a dto converter as follows:
myField = entity.myField.let { it }
I can correctly store a null value for the UUID field, but when inspecting the GET response from my controller whenever I pass a null value for such field the body does not contain the myField at all. What is the reason for that? How does SpringBoot deal with null value for UUID.
Thanks

Unable to save uuid in elasticsearch

i need to save some data where it consist of a fields called ID which is an uuid im using golang and olivere elastic search package here is my code
type Space struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
}
After doing some conversions
js := string(data)
// upto this place there is no error or warnings
ind, err := esclient.Index().
Index(Type).
BodyJson(js).
Do(ctx)
Here is the error it throws
failed to parse field [id] of type [long] in document with id
'gPmI8HIBCIO6Ejb-Y51D'. Preview of field's value:
'a5c723c5-1f6e-457f-9556-47b7ebcfd183'
The Error message is very clear that you are trying to store a5c723c5-1f6e-457f-9556-47b7ebcfd183 which is a string and not long as id field is mapped as long in your elasticsearch mapping.
It's even also telling that you got an error for document with _id having gPmI8HIBCIO6Ejb-Y51D as value, so you can find this document and correct it.
Please send the proper value of the below field, valid long in your case in order to solve the issue.
ID string `json:"id"`
Refer this code from Elasticsearch which parse the values and throws the exception, if you want to get more code level details.

Golang Decode a BSON with special character Keys to a struct

I have a Golang struct called Person where all the properties have to be exported:
type Person struct {
Id string
Name string
}
Now I need to encode my MongoDB BSON response to this Person struct. The BSON looks like:
{
"_id": "ajshJSH78N",
"Name": "Athavan Kanapuli"
}
The Golang code to encode the BSON is:
mongoRecord := Person{}
c := response.session.DB("mydb").C("users")
err := c.Find(bson.M{"username": Credentials.Username, "password": Credentials.Password}).One(&mongoRecord)
The Problem:
_id is not getting encoded into Id
If I change the Person property into _Id, then it won't be exported.
How can I solve this problem?
Define your struct with json tag-
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
I tried to put a json tag like ,
type Person struct {
Id string `json:"_id"`
Name string // this field match with json, so mapping not need
}
But still it didn't work. Because the Mongodb returns '_id' which is of type bson.ObjectId . Hence changing the Struct tag to bson:"_id" and the type of the Person struct has been changed from string to bson.ObjectId. The changes done are as follows ,
type Person struct {
Id bson.ObjectId `bson:"_id"`
Name string
UserName string
IsAdmin bool
IsApprover bool
}
And It works!

Golang GORM invalid association

I'm trying to write a very simple belongsTo association with GORM, but with primary keys that isn't Id.
My structs are as such:
type State struct {
FIPS string `gorm:"type:char(2);primary_key;column:FIPS"`
Name string `gorm:"not null"`
Area float64 `gorm:"type:real;not null"`
}
type ZipCode struct {
ZipCode string `gorm:"type:char(5);primary_key;"`
Name string `gorm:"not null"`
State State `gorm:"ForeignKey:StateFIPS;AssociationForeignKey:FIPS"`
StateFIPS string `gorm:"type:char(2);column:state_FIPS;not null"`
}
and with the following code:
var zc ZipCode
var s State
db.Model(&zc).Related(&s)
I get the error: [2017-05-18 14:26:13] invalid association [] and a find on the zipcode doesn't load the state. Does GORM not like non-Id primary keys or am I missing something?
With your current code :
var zc ZipCode
var s State
db.Model(&zc).Related(&s)
You are not set anything to your zc variable. so that's why you get an error of invalid association [] with an empty data.
To fix this you must get the ZipCode data from your database like :
db.First(&zc, 1) // find ZipCode with id 1.
and then you can associate your zc full code would be :
var zc ZipCode
var s State
db.First(&zc, 1) // find ZipCode with id 1.
db.Model(&zc).Related(&s)
Note : I'm not testing this actual code but I think it would fix the problem.

Resources