#Id generated value in monogdb spring mvc - spring

I am trying to generate different id for my db but it keep generate 0 and delete the old record how can i generate id in this code knowing that i need the id to be int for front end angular service .
#Document(collection = "tasks")
public class Task {
#Id
#Field(value = "task_id")
private int id;
#Field(value = "task_name")
private String taskName;
#Field(value = "task_description")
private String taskDescription;
#Field(value = "task_priority")
private String taskPriority;
#Field(value = "task_status")
private String taskStatus;
#Field(value = "task_archived")
private int taskArchived = 0;
//set and get
}

i found two ways to do it first one
private static final AtomicInteger counter = new AtomicInteger();
public static int nextValue() {
return counter.getAndIncrement();
}
/*******************/
#Id
#Field(value = "task_id")
private int id = nextValue();
second one i consider it a trick is to use current Date as an integer
private int id = (int) (new Date().getTime()/1000);

The simplest way is two generate unique ID with one of method provided by Java
UUID ( Universal Unique ID)
SecureRandom and MessageDigest
UID
Atomic Integer increments (that is what you need)
And many other methods
Depending on your needs pick the most suitible one. Here is a method with AtomicInteger which solves your issue :
#Document(collection = "tasks")
public class Task {
#Id
#Field(value = "task_id")
private int id;
#Field(value = "task_name")
private String taskName;
#Field(value = "task_description")
private String taskDescription;
#Field(value = "task_priority")
private String taskPriority;
#Field(value = "task_status")
private String taskStatus;
#Field(value = "task_archived")
private int taskArchived = 0;
#Transient
private AtomicInteger incrementor = new AtomicInteger(0);
public Task() {
id = incrementor.incrementAndGet(0);
}
//set and get
}
Also you have to use #Transient to avoid the incrementor being persisted in the document store.

Related

How to create Search Functionality using Optional Parameter in Spring Boot

I want to build a search functionality in my application. There are many parameters which can be optional.
Model
#Getter
#Setter
#EqualsAndHashCode(exclude = "inventoryInspectionReport")
#NoArgsConstructor
#Entity()
public class Inventory {
#SequenceGenerator(
name = "car_inventory_sequence",
sequenceName = "car_inventory_sequence",
allocationSize = 1
)
#Id
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "car_inventory_sequence"
)
private Long id;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private String owner;
#Column(nullable = false)
private String km_driven;
#Column(nullable = false)
private Integer price;
#Column
private String fuelType;
#Column
private String location;
#Column
private String insuranceValidity;
#Column
private String rto;
}
Controller
#GetMapping("/buy-car")
public String showBuyCarPageList(Model model,
#RequestParam("page") Optional<Integer> page,
#RequestParam("size") Optional<Integer> size
){
int currentPage = page.orElse(1);
int pageSize = size.orElse(16);
Page<Inventory> pageObj = carInventoryService.listAllCarIfShow(currentPage, pageSize);
int totalPages = pageObj.getTotalPages();
long totalItems = pageObj.getTotalElements();
List<Inventory> carInventoryList = pageObj.getContent();
model.addAttribute("currentPage", 1);
model.addAttribute("totalPages", totalPages);
model.addAttribute("totalItems", totalItems);
model.addAttribute("carInfo", carInventoryList);
return "frontend/buy-car-list";
}
#Service
#AllArgsConstructor
public class InventoryServiceImpl implements InventoryService {
#Autowired
private Environment env;
InventoryRepository carInventoryRepository;
InventoryImagesRepository carInventoryImagesRepository;
#Override
public Page<Inventory> listAllCarIfShow(int pageNumber, int pageSize) {
Pageable pageable = PageRequest.of(pageNumber - 1, pageSize);
return carInventoryRepository.findAllByShow(true, pageable);
}
}
My question is, how i can create a search functionality? There can be some parameter null? How i can query or ignore the parameters?
Bellow is query samples
http://localhost:8080/buy-car?page=1&size=1&name=Car2
http://localhost:8080/buy-car?page=1&size=1&name=Car2&owner=1st
http://localhost:8080/buy-car?page=1&size=1&fuelType=Petrol&owner=1st
Sample form image
Assuming that you are using JPA. You can handle it by writing a query as below. This will ignore the where condition if the parameter is null.
#Repository
public class InventoryRepository extends JPARepository<Inventory, Long> {
#Query("SELECT i FROM Inventory i WHERE (:name is null or i.name = :name) and (:owner is null or i.owner = :owner)")
Page<Inventory> findAllByShow (String name, String owner, Pageable pageable);
}
PS: You need to update your Controller and Service layers to accept other parameters such as name, owner etc..

Add Additional ObjectClass with Spring Data LDAP programmatically while creating

is There a way to return the objectClasses when creating a Object in Spring Data LDAP programmatically?
I want to create a dataModel that most of the time has two objectClasses but occationally needs a third objectClass depending on the state of one attribute.
I Tried the following but it did not work:
#Setter
#Getter
#Entry(objectClasses={"objectClassA", "objectClassB"})
public class MyDataModel implements Persistable<Name>, Serializable {
#Transient
private static final long serialVersionUID = 4589047820223901953L;
/**
* DN der TechId im IDM-Vault
*/
#Id
private Name dn;
#Attribute(name = "objectClass")
private Set<String> objectClass;
//attribute of objectClassA
#Attribute(name = "attributeA")
private String attributeA;
//attribute of objectClassB
#Attribute(name = "attributeB")
private String attributeB;
//attribute of objectClassC
#Attribute(name = "attributeC")
private String attributeC;
public MyDataModel(){
}
public MyDataModel(Name dn, String attributeA){
this.isNew = true;
this.dn = dn;
this.attributeA = attributeA;
objectClass = new HashSet<String>();
objectClass.add("objectClassA");
objectClass.add("objectClassB");
if(attributeA.equals("some_value")){
objectClass.add("objectClassC");
}
}
public Set<String> getObjectClass() {
return objectClass;
}
}

Sprint error querying embedded documents in mongoDB

I have a
#Data
#Document(collection = "req_language")
public class Language implements ChangeDto {
#Id
private String id = UUID.randomUUID().toString();
private String name;
private String code;
private Boolean active = Boolean.TRUE;
private Boolean deleted = Boolean.FALSE;
private Date changeAt = Date.from(Instant.now());
private String changedBy;
private String correlationId = UUID.randomUUID().toString();
}
And
#Data
#Document(collection = "req_locale")
public class Locale implements ChangeDto {
#Id
private String id = UUID.randomUUID().toString();
private String description;
private Language language;
private String code;
private String fatherCode;
private Boolean active = Boolean.TRUE;
private Boolean deleted = Boolean.FALSE;
private Date changedAt = Date.from(Instant.now());
private String changedBy;
private String correlationId = UUID.randomUUID().toString();
}
With a simple repository
#Repository
#JaversSpringDataAuditable
public interface LocalesRepository extends MongoRepository<Locale, String>, LocalesCustom {
List<Locale> findByCode(String code);
}
If a try to use the findByCode, I receive this error:
No converter found capable of converting from type [java.lang.String] to type [XXX.Language]
When I try to use query in the LocalesCustom, for example (empty)
Query query = new Query();
List<Locale> localeList = mongoTemplate.find(query, Locale.class);
Same error
I have tried #DBRef in Language, and popped others errors (I couldn't query by the language code, query.addCriteria(Criteria.where("language.code")) in LocalesRepository.
There's a right way to do it?

Springboot query criteria : mongodb

I have list of filtered Id as following:
filteredId=[5,44,221,34,111...]
and class Device.java:
#NotBlank
private String applicationId;
// #NotBlank
private String deviceTypeId;
#NotBlank
private String uid;
#NotBlank
private String name;
private String userId;
private String nodeId;
private String externalId;
private String softwareReleaseId;
private boolean enabled = CoreConstant.DEFAULT_ENABLED;
private boolean nameOverridden = KronosConstants.NAME_OVERRIDDEN_DEFAULT;
private Map<String, String> info = new HashMap<>();
//Getter Setter
I want to fetch all Devices which have deviceTypeId equals filteredId
I am doing something like this:
Query query = new Query();
for (int i = 0; i < filteredId.size(); i++) {
query.addCriteria(Criteria.where(filteredId.get(i)).is(device.getId()));
}
return this.MongoOperations.find(query, Device.class);
Can anyone help me with what changes I need?
try
List<Integer> filteredId = List.of(5,44,221,34,111);
Criteria criteria = Criteria.where("deviceTypeId").in(filteredId);
return mongoOperations.find(Query.query(criteria), Device.class);

How To Create Method Extend from CrudRepository for Composite Key

I have 1 class ContainerLoadList with Composite Key ContainerLoadListPK like this
#Embeddable
public class ContainerLoadListPK implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3526479259987259367L;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 13)
#Column(name = "ContainerNo")
private String containerNo;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 6)
#Column(name = "VesselCode")
private String vesselCode;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 8)
#Column(name = "Voyage")
private String voyage;
public ContainerLoadListPK() {
}
public ContainerLoadListPK(String containerNo, String vesselCode, String voyage) {
this.containerNo = containerNo;
this.vesselCode = vesselCode;
this.voyage = voyage;
}
public String getContainerNo() {
return containerNo;
}
public void setContainerNo(String containerNo) {
this.containerNo = containerNo;
}
public String getVesselCode() {
return vesselCode;
}
public void setVesselCode(String vesselCode) {
this.vesselCode = vesselCode;
}
public String getVoyage() {
return voyage;
}
public void setVoyage(String voyage) {
this.voyage = voyage;
}
}
and I have another interface extended from CrudRepository like this
public interface ContainerLoadListRepository extends CrudRepository<ContainerLoadList, ContainerLoadListPK> {
List<ContainerLoadList> findByBNo(#Param("bNo") String bNo);
#Query(name = "ContainerLoadList.findByVesselCodeAndVoyage")
List<ContainerLoadList> findByVesselCodeAndVoyage(#Param("vesselCode") String vesselCode,#Param("voyage") String voyage);
}
Are You Have Another Solution for findByVesselCodeAndVoyage without using #Query?
Assuming the embedded key field inside ContainerLoadList is called pk, you can try this:
List<ContainerLoadList> findByPkVesselCodeAndPkVoyage(String vesselCode, String voyage);
For more information, check the Spring Data JPA Property Expressions documentation.

Resources