How to put two unique fields in spring boot mongodb - mongodb

I'm trying to create two unique fields in spring mongodb but without success I'm using:
#CompoundIndex(def = "{'product_id': 1, 'ip': 1}", unique = true)
Follow my entire class:
#Setter #Getter
#CompoundIndex(def = "{'product_id': 1, 'ip': 1}", unique = true)
#Document(collection = "star_rating")
public class Star_ratingMongo extends AuditMetadata implements Persistable<Long>{
#Id
#JsonProperty("product_id")
private Long product_id;
#JsonProperty("id_collection")
private Long emberId;
public Long getEmberId() {
return product_id;
}
#JsonProperty("ip")
private String ip;
#JsonProperty("star")
private Integer star;
#Override
#Nullable
public Long getId() {
return product_id;
}
#Override
public boolean isNew() {
return !persisted;
}
}
Does anyone know where I'm going wrong?

[SOLVED]
To solve the problem I found the following code:
#Configuration
#DependsOn("mongoTemplate")
public class CollectionsConfig {
#Autowired
private MongoTemplate mongoTemplate;
#PostConstruct
public void initIndexes() {
mongoTemplate.indexOps(Star_ratingMongo.class)
.ensureIndex(new Index().on("product_id", Sort.Direction.DESC)
.on("ip", Sort.Direction.DESC).unique());
}
}

Related

#Transactional in spring JPA

I have a spring boot application where I need to update a migratedCustomer db table based on userId and phoneNumber.
Since I have to use for loop in the service layer for every update, it is creating a
new transaction and performance is hampered.
how could I make sure only one transaction is created and hence to improve the performance. code is like below
#Entity
#Table(name = "MigratedCustomer")
public class MigratedCustomer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userId;
private String phoneNumber;
#Temporal(TemporalType.TIMESTAMP)
private Date createdTimestamp;
private int batchNumber;
private String comment;
}
public class MigratedCustomerService {
#Autowired
private UserRepository userRepository;
public void updateMsisdn(List<MigratedCustomer> savedCustomers) {
for (MigratedCustomer savedCustomer : savedCustomers) {
userRepository.updateStatus(savedCustomer.getUserId(),
savedCustomer.getPhoneNumber());
}
}
}
public interface MsisdnRepository extends JpaRepository<Msisdn, Long> {
#Modifying
#Query(value = "UPDATE Msisdn SET status=INACTIVE where userId=:userId and phoneNumber=:phoneNumber",
nativeQuery = true)
void updateStatus(#Param("userId") String userId, #Param("phoneNumber") String phoneNumber);
}

How to find the specified field in spring-data-jpa

I want to find the specified field with the interface which extends JpaSpecificationExecutor.but i have not idea.
for example,i just need to find id,nickname in the user entity,what shall I do?
#Service
public class UserService {
public Page<User> findAll(User user, Pageable pageable) {
List<Predicate> predicates = new ArrayList<>();
if (user != null) {
//some condition
}
query.where(predicates.toArray(new Predicate[predicates.size()]));
return query.getRestriction();
}
}
#Repository
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
#Data
#Entity
#Table(name = "sys_user")
public class Note implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false, unique = true)
private String email;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String nickname;
}
Here is answer on your question: https://www.baeldung.com/spring-data-jpa-projections .

MongoDB Aggregtation Pipleline using Spring Boot [duplicate]

I am using spring data Mongodb in my project and refer the below classes for my query on grouping the results:
Student class:
#Document(collection = "student")
public class Student {
#Id
private String id;
private String firstName;
private String lastName;
//other fields
//getters & setters
}
StudentResults (dto):
public class StudentResults {
private String firstName;
private List<String> studentIds; //I need List<Student> here
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public List<String> getStudentIds() {
return studentIds;
}
public void setStudentIds(List<String> studentIds) {
this.studentIds = studentIds;
}
}
StudentServiceImpl class:
public class StudentServiceImpl implements StudentService {
#Autowired
private MongoTemplate mongoTemplate;
public List<StudentResults> findStudentsGroupByFirstName() {
TypedAggregation<Student> studentAggregation =
Aggregation.newAggregation(Student.class,
Aggregation.group("firstName").
addToSet("id").as("studentIds"),
Aggregation.project("studentIds").
and("firstName").previousOperation());
AggregationResults<StudentResults> results = mongoTemplate.
aggregate(studentAggregation, StudentResults.class);
List<StudentResults> studentResultsList = results.getMappedResults();
return studentResultsList;
}
}
Using the above code, I am able to retrieve the List<String> studentIds successfully, but I need to retrieve List<Student> students using Aggregation.group()? Can you help?
Change your TypedAggregation part to below and add students field to StudentResults
TypedAggregation<Student> studentAggregation = Aggregation.newAggregation(Student.class,
Aggregation.group("firstName").
push("$$ROOT").as("students"));
$$ROOT will push the whole document.
Update:
TypedAggregation<Student> studentAggregation = Aggregation.newAggregation(Student.class,
Aggregation.group("firstName").
push(new BasicDBObject
("_id", "$_id").append
("firstName", "$firstName").append
("lastName", "$lastName")).as("students"));

Nested Embedding in Kundera

I have 2 Embeddable objects and 1 Entity object. I want to use first Embeddable object inside another. Currently its not working for me. Below is the code
Class 1
#Embeddable
public class Object1{
public Object1{
}
#Column(name = "name")
String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
Class 2
#Embeddable
public class Object2{
public Object2{
}
#Column(name = "name")
String name;
#Embedded
#Column(name = "object1")
Object1 object1;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public Object1 getObject1(){
return object1;
}
public void setObject1(Object1 object1){
this.object1 = object1;
}
}
Entity Class
#Entity
#Table(name = "xxx", schema = "yyy#zzz")
public void EC{
public EC(){
}
#Embedded
#Column(name = "object2")
Object2 object2;
public Object2 getObject2(){
return object2;
}
public void setObject2(Object2 object2){
this.object2 = object2;
}
}
When I run this program, only name of Object2 is getting saved but not the embedded Object1
Is this structure is possible in Kundera? Or what am I doing wrong?
allowed only for Cassandra's composite partition key
-Vivek

Copy Entity ID at persist time

I want to copy the entity's UUID, generated at run time to another field.
The entity id is generated via the code described bellow:
package eclipselink.example;
public class UUIDSequence extends Sequence implements SessionCustomizer {
public UUIDSequence() {
super();
}
public UUIDSequence(String name) {
super(name);
}
#Override
public Object getGeneratedValue(Accessor accessor,
AbstractSession writeSession, String seqName) {
return UUID.randomUUID().toString().toUpperCase();
}
...
public void customize(Session session) throws Exception {
UUIDSequence sequence = new UUIDSequence("system-uuid");
session.getLogin().addSequence(sequence);
}
}
Persitence.xml:
property name="eclipselink.session.customizer" value="eclipselink.example.UUIDSequence"
The entity:
public abstract class MyEntity{
private String id;
private String idCopy;
#Id
#Basic(optional = false)
#GeneratedValue(generator="system-uuid")
#XmlElement(name = "ID")
public String getId() {
return id;
}
}
How can I instruct JPA (Eclipse-link) to copy the UUID generated at runtime to idCopy field as well?
I'm not 100% sure this will work (I don't know if EclipseLink calls the setter or assigns the field directly), but give this a try:
public abstract class MyEntity{
private String id;
private String idCopy;
#Id
#Basic(optional = false)
#GeneratedValue(generator="system-uuid")
#XmlElement(name = "ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
this.idCopy = id;
// or
// this.setIdCopy(id);
}
}