|
13 | 13 | import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
|
14 | 14 |
|
15 | 15 | public class MongoDBConnection {
|
16 |
| -MongoClient mongoClient; |
17 | 16 |
|
18 |
| -public void connectMongoDB() { |
19 |
| -mongoClient = MongoClients.create(); |
20 |
| -System.out.println("Connect MongoDB successful!"); |
| 17 | +public static MongoClient connectMongoDB() { |
| 18 | +return MongoClients.create(); |
21 | 19 | }
|
22 | 20 |
|
23 |
| -public void connectMongoDB(String ip, int port) { |
24 |
| -mongoClient = MongoClients.create("mongodb://" + ip + ":" + port); |
25 |
| -System.out.println("Connect MongoDB successful!"); |
| 21 | +public static MongoClient connectMongoDB(String ip, int port) { |
| 22 | +return MongoClients.create("mongodb://" + ip + ":" + port); |
26 | 23 | }
|
27 | 24 |
|
28 |
| -public void connectMongoDBWithPOJOs(String ip, int port) { |
| 25 | +public static MongoClient connectMongoDBWithPOJOs(String ip, int port) { |
29 | 26 | ConnectionString connectionString = new ConnectionString("mongodb://" + ip + ":" + port);
|
| 27 | + |
30 | 28 | CodecRegistry pojoCodecRegistry = CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build());
|
31 | 29 | CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
|
| 30 | + |
32 | 31 | MongoClientSettings clientSettings = MongoClientSettings.builder()
|
33 | 32 | .applyConnectionString(connectionString)
|
34 | 33 | .codecRegistry(codecRegistry)
|
35 | 34 | .build();
|
36 |
| -mongoClient = MongoClients.create(clientSettings); |
37 |
| -System.out.println("Connect MongoDB successful!"); |
38 |
| -} |
39 | 35 |
|
40 |
| -public MongoClient getMongoClient() { |
41 |
| -return mongoClient; |
| 36 | +return MongoClients.create(clientSettings); |
42 | 37 | }
|
43 | 38 |
|
44 |
| -public void setMongoClient(MongoClient mongoClient) { |
45 |
| -this.mongoClient = mongoClient; |
| 39 | +public static void main(String[] args) { |
| 40 | +connectionExample(); |
46 | 41 | }
|
47 | 42 |
|
48 |
| -public static void main(String[] args) { |
49 |
| -MongoDBConnection mongoDbConnection = new MongoDBConnection(); |
50 |
| -mongoDbConnection.connectMongoDBWithPOJOs("localhost", 27017); |
51 |
| -MongoDatabase mongoDatabase = mongoDbConnection.getMongoClient().getDatabase("HungcDev"); |
| 43 | +private static void connectionExample() { |
| 44 | +MongoClient mongoClient = MongoDBConnection.connectMongoDBWithPOJOs("localhost", 27017); |
| 45 | +MongoDatabase mongoDatabase = mongoClient.getDatabase("HungcDev"); |
52 | 46 | mongoDatabase.createCollection("User");
|
53 | 47 | }
|
| 48 | + |
54 | 49 | }
|
0 commit comments