logo
down
shadow

Mongo java driver cannot find public constructor for interface


Mongo java driver cannot find public constructor for interface

By : user3099635
Date : January 11 2021, 03:34 PM
should help you out The example provided in the link works perfectly fine. Much credit goes to that user for this answer.
You have probably inserted the records when FilterInterface was a class or before using the discriminators.
code :
package org.bson.codecs.chng;

import com.google.common.collect.Lists;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.ClassModel;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;

import java.util.Arrays;
import java.util.List;

public class MongoInterfaceTest {

    private static MongoClient mongoClient;

    static {
        init();
    }

    public static void init() {
        try {
            ClassModel<User> userClassModel = ClassModel.builder(User.class).enableDiscriminator(false).build();
            ClassModel<JavaUser> javaUserClassModel = ClassModel.builder(JavaUser.class).enableDiscriminator(false).build();
            ClassModel<PythonUser> pythonUserClassModel = ClassModel.builder(PythonUser.class).enableDiscriminator(false).build();
            ClassModel<TestUser> testUserClassModel = ClassModel.builder(TestUser.class).enableDiscriminator(false).build();

            CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(
                    MongoClientSettings.getDefaultCodecRegistry(),
                    CodecRegistries.fromProviders(
                            PojoCodecProvider.builder()
                                    .register(
                                            userClassModel,
                                            javaUserClassModel,
                                            pythonUserClassModel,
                                            testUserClassModel
                                    )
                                    .build()
                    )
            );

            mongoClient = MongoClients.create(
                    MongoClientSettings.builder()
                            .codecRegistry(pojoCodecRegistry)
                            .applyConnectionString(new ConnectionString(ApplictaionConfig.MONGODB_URL))
                            .applyToConnectionPoolSettings(builder -> {
                                builder.minSize(10);
                            })
                            .build()
            );
        } catch (Exception e) {
            System.out.println("Connection mongodb failed");
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) {
        MongoCollection<TestUser> collection = getMongoCollection("TestUser", TestUser.class);

        JavaUser javaUser = new JavaUser<Integer>("a");
        PythonUser pythonUser = new PythonUser<String>("b", "1");

        TestUser testUser = new TestUser(javaUser.name, javaUser);
        insertOne(collection, testUser);

        testUser = new TestUser(pythonUser.name, pythonUser);
        insertOne(collection, testUser);


        Bson bson = Filters.and(Filters.eq("name", "a"));
        TestUser testUser1 = findFirst(collection, bson);
        System.out.println(testUser1);
        testUser1.users.forEach(x -> System.out.println(x.dev()));

        bson = Filters.and(Filters.eq("name", "b"));
        testUser1 = findFirst(collection, bson);
        System.out.println(testUser1);
        testUser1.users.forEach(x -> System.out.println(x.dev()));

    }

    /**
     * 获得collection对象
     */
    public static <T> MongoCollection<T> getMongoCollection(String collectionName, Class<T> tClass) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase("kikuu");
        MongoCollection<T> collection = mongoDatabase.getCollection(collectionName, tClass);
        return collection;
    }

    public static <T> void insertOne(MongoCollection<T> collection, T document) {
        insertMany(collection, Lists.newArrayList(document));
    }

    public static <T> void insertMany(MongoCollection<T> collection, List<T> documents) {
        collection.insertMany(documents);
    }

    public static <T> T findFirst(MongoCollection<T> collection) {
        return (T) collection.find().first();
    }

    public static <T> T findFirst(MongoCollection<T> collection, Bson bson) {
        return (T) collection.find(bson).first();
    }

    public static interface User<T> {
        String dev();

        T foo();
    }

    public static class JavaUser<T> implements User<T> {
        public String name;


        public JavaUser() {
        }

        public JavaUser(String name) {
            this.name = name;
        }

        @Override
        public String dev() {
            return "java";
        }

        @Override
        public String toString() {
            return "JavaUser{" +
                    "name='" + name + '\'' +
                    '}';
        }

        @Override
        public T foo() {
            return null;
        }
    }

    public static class PythonUser<T> implements User<T> {
        public String name;
        public String age;

        public PythonUser() {
        }

        public PythonUser(String name, String age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String dev() {
            return "python";
        }

        @Override
        public String toString() {
            return "PythonUser{" +
                    "name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    '}';
        }

        @Override
        public T foo() {
            return null;
        }
    }

    public static class TestUser {
        public String name;
        public List<User> users;

        public TestUser() {
        }

        public TestUser(String name, User... users) {
            this.name = name;
            this.users = Arrays.asList(users);
        }

        @Override
        public String toString() {
            return "TestUser{" +
                    "name='" + name + '\'' +
                    ", user=" + users +
                    '}';
        }
    }
}


Share : facebook icon twitter icon
Mongo Java Driver find method deprecated

Mongo Java Driver find method deprecated


By : user10070
Date : March 29 2020, 07:55 AM
this one helps. You can set the read preference on multiple levels: the client, the database, the collection and finally on individual query.
If you set the read preference on the MongoClient with
code :
mongoClient.setReadPreference(secondary());
collection.setReadPreference(primary());
Upgrading mongo search from runCommand to find using Java driver

Upgrading mongo search from runCommand to find using Java driver


By : Aditya Diwakar
Date : March 29 2020, 07:55 AM
I hope this helps . I found this interesting page: http://api.mongodb.org/java/current/
it appears that find can take a second DBObject which has the fields.
code :
BasicDBObject fields = new BasicDBObject();
fields.append("score", new BasicDBObject("$meta", "textScore"));
DBCursor cursor = coll.find(query, fields);
How can I do this search db.collection.find( { foo: /^bar$/i } ); on mongo but using Mongo Java Driver

How can I do this search db.collection.find( { foo: /^bar$/i } ); on mongo but using Mongo Java Driver


By : user3035074
Date : March 29 2020, 07:55 AM
it should still fix some issue I 'm trying to make a case insensitive query in mongodb using java driver. I have a string for example "abcdef" in a field named foo when I search for "abc" the search must return empty, but it always return the element that contains "abcdef". , You can use Pattern like ^(abc) E.g.
code :
    Pattern compile = Pattern.compile("^(abc)", Pattern.CASE_INSENSITIVE); 
Mongo 3.2 Java Driver - Find & Count Operations

Mongo 3.2 Java Driver - Find & Count Operations


By : bwalter
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Basically, you have two different cases:
(a) Iterate through the collection, and be ready for every number of results. This is where you use find and the FindIterable which you declared in your question.
code :
 col.count(<whateverfilter>)
Save List of interface objects using mongo driver for java

Save List of interface objects using mongo driver for java


By : MotherEarth
Date : March 29 2020, 07:55 AM
Hope this helps I have a POJO that has a list of Resources which is the interface of ResourceType1 and ResourceType2
code :
public class MongoInterfaceTest {

    private static MongoClient mongoClient;

    static {
        init();
    }

    public static void init() {
        try {
            ClassModel<User> userClassModel = ClassModel.builder(User.class).enableDiscriminator(true).build();
            ClassModel<JavaUser> javaUserClassModel = ClassModel.builder(JavaUser.class).enableDiscriminator(true).build();
            ClassModel<PythonUser> pythonUserClassModel = ClassModel.builder(PythonUser.class).enableDiscriminator(true).build();
            ClassModel<TestUser> testUserClassModel = ClassModel.builder(TestUser.class).enableDiscriminator(true).build();

            CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(
                    MongoClientSettings.getDefaultCodecRegistry(),
                    CodecRegistries.fromProviders(
                            PojoCodecProvider.builder()
                                    .register(
                                            userClassModel,
                                            javaUserClassModel,
                                            pythonUserClassModel,
                                            testUserClassModel
                                    )
                                    .automatic(true)
                                    .build()
                    )
            );

            mongoClient = MongoClients.create(
                    MongoClientSettings.builder()
                            .codecRegistry(pojoCodecRegistry)
                            .applyConnectionString(new ConnectionString(ApplictaionConfig.MONGODB_URL))
                            .applyToConnectionPoolSettings(builder -> {
                                builder.minSize(10);
                            })
                            .build()
            );
        } catch (Exception e) {
            System.out.println("Connection mongodb failed");
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) {
        MongoCollection<TestUser> collection = getMongoCollection("TestUser", TestUser.class);

        JavaUser javaUser = new JavaUser("a");
        PythonUser pythonUser = new PythonUser("b","1");

        TestUser testUser = new TestUser(javaUser.name, javaUser);
        insertOne(collection, testUser);

        testUser = new TestUser(pythonUser.name, pythonUser);
        insertOne(collection, testUser);

        Bson bson = Filters.and(Filters.eq("name", "a"));
        TestUser testUser1 = findFirst(collection, bson);
        System.out.println(testUser1);
        System.out.println(testUser1.user.dev());

        bson = Filters.and(Filters.eq("name", "b"));
        testUser1 = findFirst(collection, bson);
        System.out.println(testUser1);
        System.out.println(testUser1.user.dev());
    }

    /**
     * 获得collection对象
     */
    public static <T> MongoCollection<T> getMongoCollection(String collectionName, Class<T> tClass) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase("kikuu");
        MongoCollection<T> collection = mongoDatabase.getCollection(collectionName, tClass);
        return collection;
    }

    public static <T> void insertOne(MongoCollection<T> collection, T document) {
        insertMany(collection, Lists.newArrayList(document));
    }

    public static <T> void insertMany(MongoCollection<T> collection, List<T> documents) {
        collection.insertMany(documents);
    }

    public static <T> T findFirst(MongoCollection<T> collection) {
        return (T) collection.find().first();
    }

    public static <T> T findFirst(MongoCollection<T> collection, Bson bson) {
        return (T) collection.find(bson).first();
    }

    public static interface User {
        String dev();
    }

    public static class JavaUser implements User{
        public String name;

        public JavaUser() {
        }

        public JavaUser(String name) {
            this.name = name;
        }

        @Override
        public String dev() {
            return "java";
        }

        @Override
        public String toString() {
            return "JavaUser{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    public static class PythonUser implements User{
        public String name;
        public String age;

        public PythonUser() {
        }

        public PythonUser(String name, String age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String dev() {
            return "python";
        }

        @Override
        public String toString() {
            return "PythonUser{" +
                    "name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    '}';
        }
    }

    public static class TestUser {
        public String name;
        public User user;

        public TestUser() {
        }

        public TestUser(String name, User user) {
            this.name = name;
            this.user = user;
        }

        @Override
        public String toString() {
            return "TestUser{" +
                    "name='" + name + '\'' +
                    ", user=" + user +
                    '}';
        }
    }
}
Related Posts Related Posts :
  • Android Broadcastreceiver for other apps install/delete not working
  • Android Studio onClick not working in BindViewHolder
  • How to use Spring Converter for some controllers only?
  • How verify that 3 numbers in sequence are equals?
  • When using .compareTo to compare dates, why doesn't it take Months into account?
  • Does the perfomance of "filter then map" and "map then filter" differ in a Stream?
  • How can I set the initial Delay after pressing the start Button to a specific time (HH:mm:ss) format
  • How to switch between Android devices during the tests
  • How to configure java.util.logging via properties to use standard output?
  • How to iterate through array in order
  • Is there better way of iteration to find the evenly divisible number?
  • How to split a string to non empty words if it might include a separator like tab on first place
  • Supplier<Sequence<String>> cannot be iterated more than once
  • Why there is only one thread can actually started in @PostConstruct method?
  • Manage CompletionStage inside of Netty handler
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • Ignite persisting a Set: Cannot find metadata for object with compact footer
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org