Get Mongo db id after insertion in case of POJO class - java

I have a POJO class in java
#Data
#EqualsAndHashCode(callSuper = false)
#NoArgsConstructor
#AllArgsConstructor
public class TestModel{
protected ObjectId id;
private String name;
}
Is there any way to populate id field in case of insertion. I can see that if I use Document, then after insertion I can get objectId by using
document.get("_id");
So is there any way I can achieve same using custom POJO class.

Related

saveAndFlush in Spring data JPA

#Entity
#Table(name = "DISC")
#NoArgsConstructor
#AllArgsConstructor
#Data
#Builder
#ToString
#EqualsAndHashCode(of = { "discId" })
public class Disc implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ReturnInsert
#Column(name = "DISC_ID")
private Long discId;
..
}
and
#Repository
public interface DiscRepository extends JpaRepository<Disc, Long> {
...
}
but when I save using saveAndFlush() I have this error:
org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save():
Looks like you don't set the discId field, as simple as that.
If you want to delegate this to the framework use #GeneratedValue (and set strategy which corresponds to your DB). The framework will handle the ids generation for you.

Hibernate: how to insert foreign key id to a table

I am new to Hibernate and I am trying to save List<AuditScope> auditScopes from Audit entity using Hibernate. Audit entity has One-to-Many relationship with AuditScope entity, Audit can have many AuditScope. I am using saveAll() method to batch insert auditScopes instead of saving one by one through a loop. Unforunately, I have to loop auditScopes just to set each AuditScope's auditId(FK) manually instead of automatically. What I want is to batch insert them without looping and manually setting auditId. I am sorry my code is not good. Thank you very much.
Here are my classes:
#Entity
#Table(name="audit")
public class Audit {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="audit_gen")
#SequenceGenerator(name="audit_gen")
#Getter #Setter private int auditId;
#Getter #Setter private String auditName;
#Transient #Getter #Setter private List<AuditScope> auditScopes;
}
#Entity
#Table(name="auditScope")
public class AuditScope {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="auditScope_gen")
#SequenceGenerator(name="auditScope_gen")
#Getter #Setter private int auditScopeId;
#Getter #Setter private int auditId; //FK
#Getter #Setter private String scope;
}
Here's my insertAudit() method
public void insertAudit(Audit audit){
//Save Audit first to get auditId
Audit theAudit = auditRepository.save(audit);
//Loop audit.getAuditScopes() to manually set auditId
for(AuditScope scope : audit.getAuditScopes()){
scope.setAuditId(theAudit.getAuditId());
}
//Save all AuditScope with set auditId
auditScopeRepository.saveAll(audit.getAuditScopes());
/*
Expected result
auditRepository.save(audit);
auditScopeRepository.saveAll(audit.getAuditScopes());
*/
}

Spring Data Couchbase Object id

I'm trying to create a Document with an #Id property different from String, everything works great. My issue is the way the document is stored in the Bucket, unfortunately it prefixes with the Class name:
ActorKey(key=d7471027-4bd1-40a3-8e29-5249f45beed4)
{
"name": "Emma Watson",
"_class": "com.guilherme.miguel.domain.Actor"
}
Is there a way to store the id like if it was a simple String?
This is to avoid issues in plain queries (simple queries will force me to use ActorKey(key=xxxxxxxxxxx))
Actor.java:
#Data
#AllArgsConstructor
#NoArgsConstructor
#Document
public class Actor {
#Id
private ActorKey key;
private String name;
}
ActorKey.java:
#Data
#AllArgsConstructor
#NoArgsConstructor
public class ActorKey implements Serializable {
private String key;
}
ActorRepository.java
#N1qlPrimaryIndexed
#ViewIndexed(designDoc = "actor")
public interface ActorRepository extends CouchbaseRepository<Actor, ActorKey> {
}
The underlying Couchbase SDK uses String as a Document identifier, so spring-data-couchbase will call toString() on your key objects. What you see is the result of the Lombok-generated toString() method (a generation that is part of the #Data annotation).
Simply explicitly override toString() in ActorKey!

Trouble mapping XML to a list of POJOs in Jackson

I need to take XML that looks like something like the following:
<root:ElementName>
<equipment:Equipment>
<eqp:Name>Equipment 1</eqp:Name>
<eqp:Type>A</eqp:Type>
</equipment:Equipment>
<equipment:Equipment>
<eqp:Name>Equipment 2</eqp:Name>
<eqp:Type>B</eqp:Type>
</equipment:Equipment><equipment:Equipment>
<eqp:Name>Equipment 3</eqp:Name>
<eqp:Type>C</eqp:Type>
</equipment:Equipment>
</root:ElementName>
And I want to map that into a list of "Equipment" POJOs. I'm using Jackson XML mapping and Lombok, so basically I've got this split into two classes right now, first the root object which should read in that <root:ElementName> and turn all the <equipment:Equipment> tags into a list of equipment objects:
#JacksonXmlRootElement(localName = "root:ElementName")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class EquipmentMidbCompositeResponse
{
#JsonProperty("equipment")
#JacksonXmlProperty(localName = "equipment:Equipment")
#Getter
#Setter
List<Equipment> equipmentList;
}
And then the Equipment object itself:
#Entity
#Data
#NoArgsConstructor
#EqualsAndHashCode(callSuper = true)
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public final class Equipment
{
#JsonCreator
public Equipment(String name){
}
#JsonProperty("EquipmentName")
#JacksonXmlProperty(localName = "eqp:Name")
#Setter
#Getter
private String name;
#JsonProperty("EquipmentType")
#JacksonXmlProperty(localName = "eqp:Type")
#Setter
#Getter
private String type;
}
At first I didn't have that constructor with #JsonCreator in the Equipment object and would get a "no String-argument constructor/factory method to deserialize from String value" error, and after some research added the constructor to get around that. With that I get past that error, but the list of Equipment objects that gets returned after mapping have all their fields set to null. What am I missing/doing wrong here when trying to map these XML properties?
(Posted on behalf of the OP).
I figured out the issue, my approach with the #JsonCreator was the incorrect way to go for that error. Turns out all I had to do was an a #JacksonXmlElementWrapper(useWrapping=false) annotation to my list item and everything went through just fine.

Add validation rules to Pojo.name to object extending Pojo?

I have a simple java pojo which i give to my android users:
#XmlRootElement
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class PostAccount {
#Getter
#Setter
private String email;
#Getter
#Setter
private String pass1;
#Getter
#Setter
private String pass2;
}
This pojo is serialized to json and send to my server. On my server i which to use jersey bean validation:
public NumberResult add(#Valid ValidAccount account) {
But because the Account pojo doesn't have any validation annotations validation doesn't do much.
I can create a second pojo with validation annotations and use that on server side:
public class ValidAccount {
#Getter
#Setter
#NotEmpty
#CheckEmail
private String email;
#Getter
#Setter
#NotBlank
private String pass1;
#Getter
#Setter
#NotBlank
private String pass2;
}
Works perfectly.
But when i now add a field at Account pojo i do have to remember to change ValidAccount pojo. No problem, but when you have a lot of pojo's things get complicated to manage.
Is there a better solution?
For example is it possible to extends the Account pojo and in a way add the validation rules? (please i which to continue using annotations, xml gives me the creeps)

Categories