Difference between MongoSpringData id and _id - spring

I am using MongoDB community edition 4.2 on Windows 10 and inserting some documents. My requirement is to store some documents containing 'id' as field name while MongoDB is replacing it with '_id' and making it the primary key. Is it possible to disable this feature and store key '_id' as the separate autogenerated primary key column and store 'id' as well in separated column which is part of my document?
We are using Spring Data MongoDb Repository entities insertion into MongoDb. What we have observerd the entity having name 'id' as primary key get converted to _id while entities having other name like projectId or something stored as it is with another seperate column as _id generated by MongoDB as primary key. Suggestions are helpful.
Code:
#Autowired
TrackHistoryRepository trackHistoryRepository;
trackHistoryRepository.save(entity);
public interface TrackHistoryRepository extends MongoRepository<OdataEntity, String> {}
Entity:
public class CurrencyEntity implements OdataDeleteableEntity<Long> {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name="id")
private Long id;
}

MongoDB can't do that. _id in mongodb is auto-incremented and auto-generated id key for specific record or data field. And _id is primary key by default set by mongodb. You can also enter your user defined key(value) to the _id but you cant change name of field.

Related

Default Value on OneToOne Association JPA

i have a transactional entity and one of the fields is an association with a tenant.
#Entity
public class transactionalClass
....
#OneToOne
#JoinColumn(name = "tenant_id")
private Tenant tenant;
So this is generate a tenant_id (String) column in my transactionalClass but the type of my field is a object tenant type.
Now, i want to set directly a contextualised string (already have) on tenant_id column when create a new object. I have to do a getTenant and after set field(tenant object) in transactionalClass or is also possible to set string directly once i'm sure the key exists.
Thanks

Specify foreign key reference in Spring Data Rest, Update Request using HTTP PUT

I have an entity
#Entity
#Table(name="Indications")
#NamedQuery(name="Indication.findAll", query="SELECT i FROM Indication i")
public class Indication implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="IndicationID")
private int indicationID;
#Column(name="IndicationDescription")
private String indicationDescription;
#ManyToOne
#JoinColumn(name="ParentIndicationID")
private Indication indication;
}
As is evident in the entity the table has 3 columns
IndicationID which is a primary key
IndicationDescription which is a string
Indication which is a foreign key reference to a row in the same table, so it is many-to-one relationship
Since I am using Spring Data Rest I can create a new record using HTTP POST with the following body
{
"indicationDescription": "dummy1",
"indication": "/indications/1"
}
This creates a new row in the database with the content dummy1 and creates a foreign key reference to the record with id 1.
But when I try to update the foreign key reference using HTTP PUT with the following body
{
"indicationDescription": "dummy2",
"indication": "/indications/2"
}
While it updates the indicationDescription it does not actually update the foreign key reference.
I am aware that I can update the foreign key reference by using the URL http://localhost:8080/indications/7733/indication
and sending body as
http://localhost:8080/indications/2
after setting the content type to text/uri-list
My question is , Is there a way to perform the update in one request using the body similar to the one I used for creation of the record instead of making another update request using the URL - http://localhost:8080/indications/7733/indication
Thanks in advance.

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

Spring Data JDBC One-To-Many with Custom Column Name

I'm using spring-boot-starter-data-jdbc 2.4.2. In my domain aggregate I need to map a List of Strings that is populated from a column in another table. It is a legacy database so I have no control over the table and column names and need to use custom names. I see there is an #MappedCollection annotation, but can't see how to use it in this scenario. Below is my class:
#Data
#Table("NMT_MOVIE_THEATRE")
public class MovieTheatre {
#Id
#Column("MOVIE_THEATRE_ID")
private Long id;
#Column("ZIP_CODE")
private String zipCode;
// this comes from table NMT_CURRENT_MOVIE, column CM_ID, joined by MOVIE_THEATRE_ID
private List<String> currentMovieIds;
}
Using Spring Data JDBC, how can I create the one-to-many relation?
Wrap your String in a little entity.
#Table("NMT_CURRENTMOVIE")
class MovieId {
#Id
#Column("CM_ID")
final String id
// add constructor, equals and hashCode here or generate using Lombok
}
Then use it in the MovieTheatre. Since you don't have a column for an index, the proper collection to use is a Set
// ...
class MovieTheatre {
// ...
#MappedCollection(idColumn="MOVIE_THEATRE_ID")
Set<MovieId> currentMovieIds;
}
Note that equals and hashCode is important as well as the constructor taking all arguments used in those, since the entity is used in a Set.

Save composite key data to elastic search document

I am using hibernate envers to audit the data for my tables and save in Oracle DB. This auditing data I am reading and saving to elastic search index through Java code using spring data elastic search. I have a composite key (id and rev) which defines a unique row to save data but for elastic search I can't provide a composite key. It is taking only rev (identifier) column and replacing data.
Hibernate envers background information:
rev is the default identifier that hibernate is providing and for list of records which modified at same time, it creates same rev id:
Eg: id rev comments
1 1 newly created
2 1 newly created
1 2 modified
2 2 modified
First 2 rows are created at same time and next time I modified both the rows and updated so hibernate envers creates same rev id for 1 save.
#Entity
#IdClass(MyEmbeddedId.class)
#Document(indexName = "#{#indexName}", type = "my-document", shards = 1, replicas = 0, refreshInterval = "-1")
#Getter #Setter
public class MyClassAudit {
#Id
private Long id;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#org.springframework.data.annotation.Id --> (this is for elastic search _id)
private Long rev;
}
#Getter #Setter
public class MyEmbeddedId implements Serializable {
private Long id;
private Long rev;
}
Java code:
List<MyClass> list = repository.findById(id);
elasticSearchRepository.saveAll(list)
Elastic search repository interface:
public interface MyElasticSearchRepository extends GenericSearchRepository<MyClassAudit, Long> {}
When I save data to elastic search then all 4 records should be saved as given in example but only 2 records are saved like below:
_id id rev comments
1 2 1 newly created
2 2 2 modified
It is because rev is taken as identifier in elastic search and 2nd record is being updated.
How to make elastic search to consider composite key to maintain unique records?
PS: _id is the elastic search identifier. since rev is having spring data annotation id, rev is considered as identifier in elastic search
Elasticsearch itself has no concept of a composite key. Spring Data Elasticsearch takes the #Id annotated element and uses it's toString() method to create the id entry for Elasticsearch (and stores the field as well in the source).
So - without haven't tried - you could use your MyEmbeddedId class as a field property of your MyClassAudit class and annotate it with #Id. But you have to have this property in your class, it will not be synthesized.
This will probably conflict with the annotations for hibernate, but I don't think it's a good idea to share one entity between storages and using mixed annotations.

Resources