Get back autogenerated columns from database when saving an entity with Spring Data R2dbc - spring

I have an issue when I create an entity like this
#Table("event_service.EVENT")
public class Event implements Persistable<UUID> {
#Id
private UUID id;
//Autogenerated by database if null
private UUID eventId;
}
I have a normal repository like this defined:
interface EventRepository extends ReactiveCrudRepository<Event, UUID>
When I use the repository to save this entity, the entity that is return still has eventId as null and I have to refetch the entity again from the DB to get it populated correctly. I can see that the query generated does only include the ID field in the RETURNING clause of the auto generated SQL. Is there a way to get the other auto generated field back automatically on the save method?

Related

Spring Data Persist entity in Log Table before each save()

im working in a spring boot project and i have a requirement to save the old object in a specific table before each new save ; this my man entities:
#Entity
#Table(name="demande")
public class Demande {
#Id
private Long id;
// all properties
}
#Entity
#Table(name="demande_log")
public class DemandeLog {
#Id
private Long id;
// all properties
}
what im trying to do is before each demandeRepository.save(demande);
i want to save the old demande object (current row in database) as DemandeLog in my demande_log table.
do you have any idea how using spring data, i know that there is a listener #PrePersist in JPA.. but i want to do it properly.
Regards.
I recommend using Envers. It is easy to set up and gives you a complete change log.

How to make #Indexed as unique property for Redis model using Spring JPA Repository?

I have a model class that I store in Redis and I use Jpa Repository with Spring java. Normally(not with redis) jpa repository is saving the new data or updates(conditionally) if the given model is already exist in Db. Here, I want to add new item to redis but if it is not already exists on db otherwise update it just like usual Jpa implementation.
Here is my model:
#Getter
#Setter
#RedisHash("MyRecord")
public class MyRecordRedisModel {
private String id;
#Id
#Indexed
private String recordName;
private Date startDate;
private Date endDate;
}
And my repository class is just a normal spring jpa repo as follows:
#Repository
public interface IFRecordRedisRepository extends JpaRepository<IFRecordRedisModel, String> {
Page<IFRecordRedisModel> findAll(Pageable pageable);
}
Unique key must be the name (I totally do not care about uniquiness of the id). Thus, if the name is already exist in Db than do not add it again. I marked it as Indexed but still it is adding same data (with same recordName).
How can I make it unique?
This would require an additional query, but I think this solution would work for you. You can use query by Example to check if there exists a record with that name, and save conditionally, or do something else if it already exists.
IFRecordRedisModel exampleRecord = new IFRecordRedisModel();
exampleRecord.setRecordName(inputRecord.getRecordName());
if (!repository.exists(Example.of(exampleModel)))
repository.save(inputRecord);
else ..... // do something else

How to populate H2 DB UUID primary key using sql file in Spring Boot

I am developing a Spring Boot-2.4 application which use Spring Data JPA and I am writing test for my CURD implementation. I have few scenarios needs to load table data with specific primary key values before my test execution. I thought of using import.sql or data.sql in which i can write native SQL queries and use those supplied primary key values. As my primary key is defined as UUID eventhough I gave valid UUID data in SQL while fetching using findById its not working.
data.sql
insert into TEST_TABLE(id,name,pass) value ('2B12245566587878779679','test','xxxxx');
Assume given UUID value is valid and I can able to insert this data in H2 and able to view.
But when in JPA try to access this same ID using findById('2B12245566587878779679') will not returning this record. Is there any correct way to load the UUID and access it using .sql file.
EDIT: Included code sample
#Entity(name="TEST_TABLE")
public class TestTable{
#Id
#GeneratedValue
private UUID id;
}
#Repository
public interface TestTableRepository extends JpaRepository<TestTable,UUID>{}
#Service
public class TestTableService {
#Autowired
TestTableRepository testTableRepository;
public UUID getTableData(UUID id){
testTableRepository.findById(id); // here passing 2B12245566587878779679
}
}
Expecting one row returned but its not returning any

Find All based on the flag value in Spring Data JPA

I want to fetch all the records based on the flag value. Flag value can be either 'A' for Active or 'I' for Inactive.
I want to fetch both Active and Inactive records and put them in some kind of List or Map.
These are my repository and entity class:
#Repository
public interface StatusRepository extends JpaRepository<StatusEntity,Long>{
}
public class StatusEntity{
#Id
#Column(name="id_status")
private Long idStatus;
#Column(name="name")
private String name;
#Column(name="status_flg")
private String statusFlg;
}
I am able to fetch all the records using statusRepository.findAll(). I was wondering if there is something like statusRepository.findAllByStatusFlg(String flag) or statusRepository.findByStatusFlg(String flag)?
Is there any way to fetch all the records by specifying where condition on certain columns?
P.S. I am using spring-boot-starter-data-jpa 2.3.2.RELEASE
You should make yourself familiar with the basics of spring data. As you thought, you can define a query method in your StatusRepository that fetches your StatusEntitys according to your needs.
#Repository
public interface StatusRepository extends JpaRepository<StatusEntity,Long>{
List<StatusEntity> findByStatusFlg(String flag);
}

Javers: Diff DB entities with data from external source without ids

I'm getting data from an external source with no ids and then I store it in my DB. I'm using Spring with JPA (Hibernate). The ids are autogenerated on the first commit.
The changes in the external data is to be updated every night.
The first commit is trivial. I just create new entities for each new data object and save.
But further on I need to track the changes and just update the existing DB entities that have changed (and add and remove).
It doesn't matter which existing entity is to be updated.
How would I need to approach this using Javers? Is there an example?
Currently I'm thinking about something like:
Get existing entities from the DB.
Create new entities from the external data.
?
The new entities have no id. I would like to use Javers get the diff without needing any id. Diff the collections only based on the values.
Following a sample entity. None of the values apart the id is unique. Only the comparison of all other values can be used to check the identity to an existing entity.
#Entity
#Data
public class TiwHier {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#NotNull
private Long id;
#NotBlank
private String prodId;
private String pnGuid;
private String parentPnGuid;
private String typ;
private String name;
private String text;
private String klasse;
}

Resources