How to auto generate id using MongoDB and Spring Data MongoDB? - mongodb

I need to auto generate the id on my documents for persist on database. But if i don't set the id it has an error that cannot be null. How could I generate the id for reduce the repeated code and make it simple?

#Id
private ObjectId id;I found a solution that is,
must the type of the id be an org.bson.types.ObjectId, like above:
#ToString
#Getter
#NoArgsConstructor
#RequiredArgsConstructor(staticName = "of")
public class Guide {
#Id
private ObjectId id;
#NonNull
private String name;
}
The right place that are the solution is:
#Id private ObjectId id;

Related

Querying revisions of nested object using spring-data-envers

I'm trying to implement entity auditing in my Java Spring Boot project using spring-data-envers. All the entities are being created as they should, but I've come up against a brick wall when executing the query.
parentRepository.findRevisions(id).stream().map(Parent::getEntity).collect(Collectors.toList());
During this select the repository is supposed to fetch info also from the child entity, instead I get unable to find <child object> with {id}.
According to my experiments categoryId is being searched in the Category_Aud table, instead of the actual table with desired data.
Code snippets:
#Data
#Entity
#Audited
#NoArgsConstructor
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Enumerated(EnumType.STRING)
private Status status;
#Enumerated(EnumType.STRING)
private Type requestType;
private String fullName;
#ManyToOne
#JoinColumn(name = "child_id")
private Child child;
}
#Data
#Entity
#Audited
#NoArgsConstructor
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
}
I've extended Parent with RevisionRepository
#Repository
public interface ParentRepository extends RevisionRepository<Parent, Long, Long>, JpaRepository<Parent, Long>
And annotated my SpringBootApplication entry class with:
#EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
I couldn't find any explanation for this so far, how can make parentRepository get what I need?
The underlying problem here is that the reference from a versioned entity isn't really properly defined. Which variant of the reference should be returned? The one at the start of the version you use as a basis, the one at the end? The one that exists right now?
There are scenarios for which each variant makes sense.
Therefor you have to query the revisions yourself and can't simply navigate to them.

Hibernate mapping camelCase field to snake_case

I am using hibernate with postgresql. I am curious if is it possible to map for example this entity:
#Entity
#Data
#NoArgsConstructor
class User {
#Id
private Long id;
private String firstName;
private String lastName;
}
in database I have columns like first_name, last_name. I got error that I introduce wrong names (when I add for example #Column(name = "first_name"); everything is ok. How can I avoid adding #Column neither change database?

how to create an id within the embedded document using mongoDB and spring data

im trying to set a id within embedded document. in the next level in mongoDB, using spring data.
lets say i have a User document and each user has multiple Session (One-to-many), and i like to get an auto generate and unique id for the sessions. how would I do that?. I have tried to create the below entities for User & Session, but the id at session is always null!, please help
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class User {
#Id
private String id;
private String emailId;
private String firstName;
private String lastName;
private ArrayList<Session> sessions;
}
public class Session {
#Id // i like to make this id auto generated and unique
private String id;
private String status;
private String title;
//assume all Args, Getters and setters are exists
You'd need to update this unique id manually for there doesn't seem to be an automated feature doing that in spring-data-mongodb.
Something like;
public Integer generateUniqueId() {
Session latestSession = sessionRepository.findTopOrderByIdDesc(); // latest session
return Optional.ofNullable(latestSession).map(Session::getId).orElse(-1) + 1;
}
where unique id is just an incrementing counter...
& set this value to the new Session before saving it;
newSession.set(generateUniqueId());
sessionRepository.save(newSession);
For more details, check here

Repository findIn confusion

My database has an Exchanges class which contains a list of CurrencyPairs.
Is it possible to use to use a Repository method to directly obtain a CurrencyPair which matches on name within a given Exchange? I'm thinking of something like
CurrencyPairDbo findByExchangeNameAndCurrencyPairIn(...)
but I can't see quite how to tie it all together. Or do I need to write a custom query for this? And does this need to be in the ExchangeRepository or the CurrencyPairRespository?
#Entity()
#Table(name = "Exchanges")
public class ExchangeDbo {
#Id #GeneratedValue
#Getter private Long id;
#Getter private String exchangeName;
#OneToMany(mappedBy = "exchange",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.EAGER)
#BatchSize(size=100)
#Getter private List<CurrencyPairDbo> listCurrencyPair = new ArrayList<>();
...
}
#Entity()
public class CurrencyPairDbo {
#Id #GeneratedValue
#Getter private Long id;
#Column(unique=true)
private String currencyPair;
#ManyToOne(fetch=FetchType.EAGER)
#Getter private ExchangeDbo exchange;
...
}
Edit:
I'm thinking it's not Find...In that I want at all. I think that something like:
List<CurrencyPairDbo> x = exchangeRepository.findByExchangeNameLowercaseAndListCurrencyPairCurrencyPair(exchangeName.toLowerCase(), currencyPair);
might work, except that in returns an Exchange object and a:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [biz.ianw.coindatabase.database.ExchangeDbo] to type [biz.ianw.coindatabase.database.CurrencyPairDbo]
This, in the currency pair repository, seems to do the job.
I added a lower case field for matching purposes and an index for efficiency.
CurrencyPairDbo findByExchangeExchangeNameLowercaseAndCurrencyPairNameLowercase( String exchangeName, String currencyPair );

#OneToMany and #ManyToOne in MongoDB and JPA -EISOneToOneMapping cannot be cast to

We're trying to do a #OneToMany and #ManyToOne relation with EclipseLink/MongoDB:
The #OneToMany declaration looks like this:
#Entity
#NoSql(dataType = "ServiceCatalog", dataFormat = DataFormatType.MAPPED)
public class ServiceCatalog {
#Id
#GeneratedValue
#Field(name = "_id")
private String id;
#OneToMany
private List<ServiceCatalogNeedCategory> serviceCatalogNeedCategories;
…
On the other side, the #ManyToOne declaration:
#Entity
#NoSql(dataType = "NeedCategory", dataFormat = DataFormatType.MAPPED)
public class ServiceCatalogNeedCategory {
#Id
#GeneratedValue
#Field(name = "_id")
private String id;
#Field(name = "title")
private String Title;
#ManyToOne(fetch=FetchType.LAZY)
private ServiceCatalog serviceCatalog;
...
The above configuration leads to the following error:
org.eclipse.persistence.eis.mappings.EISOneToOneMapping cannot be cast to org.eclipse.persistence.mappings.OneToOneMapping
We really need to be able to resolve both directions.
Cheers
Michael
Please include the full exception stack.
There was an issue fixed in the 2.6 dev stream for NoSQL, it may be related.
https://twitter.com/j_b_sutherland/status/339727557928833025
What version are you using, I would try at least 2.5, or a recent 2.6 dev build.
You missed the MappedBy Annontation on the OneToMany side.
See http://www.objectdb.com/api/java/jpa/OneToMany
[edit]
OMG it's NOSQL sorry.
ORM are no more what they used to be..
I don't know so, but if you're really using JPA API then it might be the trick