springboot啟動mongoDB報錯之禁用mongoDB自動配置問題
springboot啟動mongoDB報錯之禁用mongoDB自動配置
錯誤信息如下:
springboot自動配置了支持mongodb。
在啟動springboot時會自動實例化一個mongo實例。
所以自己配置的話,需要禁用掉springboot的自動配置。
@SpringBootApplication(exclude = {MongoAutoConfiguration.class,MongoDataAutoConfiguration.class})
這個注解可以禁用springboot自帶的配置。
如下圖:
springboot整合MongoDB時碰到的問題
1.賬號總是不對,導致查不出數(shù)據,報錯Auth…權鑒錯誤
這次,我也是第一次接觸MongoDB,非常的生疏
springboot整合MongoDB,要在properties文件中配置賬號
mongodb基本語法:
use DATABASE_NAME; --創(chuàng)建數(shù)據庫 show dbs; --查看我們所有的庫,注意,我們剛創(chuàng)建的庫,如果沒有數(shù)據,是不會被顯示的 show users; --查看當前庫所有擁有的賬號 db.createCollection(name, options) --在當前數(shù)據庫中創(chuàng)建集合 show tables --查看當前庫中有哪些集合 --在當前數(shù)據庫中創(chuàng)建用戶并設置密碼及權限 db.createUser( ... { ... user : "aaa", ... pwd : "123456", ... roles: [ { role : "readWrite", db : "springboot" }] ... } ... )
通過上面的基礎鋪墊:
1.首先我們要登錄MongoDB數(shù)據庫
用管理員權限運行cmd
進入我們安裝的MongoDB的bin目錄下執(zhí)行命令
mongo
即可登錄MongoDB數(shù)據庫
2.創(chuàng)建數(shù)據庫
use springboot;
3.創(chuàng)建數(shù)據庫對應的賬號
創(chuàng)建一個springboot賬號,對springboot數(shù)據庫擁有讀寫權限
db.createUser( ... { ... user : "springboot", ... pwd : "123456", ... roles: [ { role : "readWrite", db : "springboot" }] ... } ... )
4.在springboot庫中創(chuàng)建集合user
db.createCollection("user"); --創(chuàng)建集合user show tables; --查看當前庫中所有的集合 --- 并給集合user添加一條數(shù)據 db.user.insert({ "user_name":"pzj", "note":"用戶pzj", "roles":[{ "role_name": "vip_user", "note": "會員" }] })
到此,MongoDB的數(shù)據庫初始化完成。
2.springboot工程代碼中的配置
主要說下properties中的配置,pom里面引入的包我就不說了
spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.username=springboot spring.data.mongodb.password=123456 spring.data.mongodb.database=springboot spring.data.mongodb.port=27017 logging.level.org.springframework.data.mongodb.core=DEBUG
3.查詢時遇見的錯誤
No converter found capable of converting from org.bson.types.ObjectId to type Long異常
這個問題很好解決
我們在創(chuàng)建實體類對應數(shù)據庫中的集合user時,把id設置成了Long型,導致的報錯
我們只要把id類型改成String即可。
在MongoDb里要求每個文檔都需要有_id 字段,java類中有如下情況會被映射為_id字段
如果1個字段加上了 @Id (org.springframework.data.annotation.Id)注解,那么將bean保存到數(shù)據庫時就會把該字段映射為文檔中的_id字段
如果java對象中沒有 @Id 注解,名字為id 的字段將會被映射為文檔中的_id字段
所以,也可以看出,我們的MongoDB數(shù)據,是不需要我們人為的添加主鍵id字段的
這個和以往的mysq等關系型數(shù)據庫有所不同
它會自動給我們生成一個_id字段,作為集合的主鍵,標識一條數(shù)據
我的操作記錄:
Microsoft Windows [版本 10.0.17134.81] (c) 2018 Microsoft Corporation。保留所有權利。 C:\WINDOWS\system32>mongo -port 27017 -u "admin" -p "123456" --authenticationDatabas Error parsing command line: unrecognised option '--authenticationDatabas' try 'mongo --help' for more information C:\WINDOWS\system32>d: D:\>cd MongoDB D:\MongoDB>cd Server D:\MongoDB\Server>cd 4.2 D:\MongoDB\Server\4.2>cd bin D:\MongoDB\Server\4.2\bin>mongo -port 27017 -u "admin" -p "123456" --authenticationDatabas Error parsing command line: unrecognised option '--authenticationDatabas' try 'mongo --help' for more information D:\MongoDB\Server\4.2\bin>mongo -port 27017 -u "admin" -p "123456" MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("92832542-8eb8-4df5-942b-671ae8e574f5") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > use admin switched to db admin > show users { "_id" : "admin.admin", "userId" : UUID("ee717096-e66e-4554-95a5-29aafd999c86"), "user" : "admin", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > exit bye D:\MongoDB\Server\4.2\bin>mongo MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("37edcce7-3eea-430a-9dca-7bf84fa70e88") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > use admin switched to db admin > > db.auth("admin","123456") 1 > show users; { "_id" : "admin.admin", "userId" : UUID("ee717096-e66e-4554-95a5-29aafd999c86"), "user" : "admin", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > exit bye D:\MongoDB\Server\4.2\bin>use admin 'use' 不是內部或外部命令,也不是可運行的程序 或批處理文件。 D:\MongoDB\Server\4.2\bin>mongo MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("25bd7adc-50a0-455c-af5d-48ad740ff1a4") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T09:38:15.970+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > use admin switched to db admin > db.auth("root","123456") Error: Authentication failed. 0 > exit bye D:\MongoDB\Server\4.2\bin>mongod --shutdown --dbpath=D:\MongodbData\db Error parsing command line: unrecognised option '--shutdown' try 'mongod --help' for more information D:\MongoDB\Server\4.2\bin>mongod --help Options: --networkMessageCompressors arg (=snappy,zstd,zlib) Comma-separated list of compressors to use for network messages General options: -h [ --help ] Show this usage information --version Show version information -f [ --config ] arg Configuration file specifying additional options --configExpand arg Process expansion directives in config file (none, exec, rest) --ipv6 Enable IPv6 support (disabled by default) --listenBacklog arg (=2147483647) Set socket listen backlog size --maxConns arg (=1000000) Max number of simultaneous connections --pidfilepath arg Full path to pidfile (if not set, no pidfile is created) --timeZoneInfo arg Full path to time zone info directory, e.g. /usr/share/zoneinfo -v [ --verbose ] [=arg(=v)] Be more verbose (include multiple times for more verbosity e.g. -vvvvv) --quiet Quieter output --port arg Specify port number - 27017 by default --logpath arg Log file to send write to instead of stdout - has to be a file, not directory --logappend Append to logpath instead of over-writing --logRotate arg Set the log rotation behavior (rename|reopen) --timeStampFormat arg Desired format for timestamps in log messages. One of ctime, iso8601-utc or iso8601-local --setParameter arg Set a configurable parameter --bind_ip arg Comma separated list of ip addresses to listen on - localhost by default --bind_ip_all Bind to all ip addresses --noauth Run without security --transitionToAuth For rolling access control upgrade. Attempt to authenticate over outgoing connections and proceed regardless of success. Accept incoming connections with or without authentication. --slowms arg (=100) Value of slow for profile and console log --slowOpSampleRate arg (=1) Fraction of slow ops to include in the profile and console log --auth Run with security --clusterIpSourceWhitelist arg Network CIDR specification of permitted origin for `__system` access --profile arg 0=off 1=slow, 2=all --cpu Periodically show cpu and iowait utilization --sysinfo Print some diagnostic system information --noscripting Disable scripting engine --notablescan Do not allow table scans --keyFile arg Private key for cluster authentication --clusterAuthMode arg Authentication mode used for cluster authentication. Alternatives are (keyFile|sendKeyFile|sendX509|x509) Replication options: --oplogSize arg Size to use (in MB) for replication op log. default is 5% of disk space (i.e. large is good) Replica set options: --replSet arg arg is <setname>[/<optionalseedhostlist >] --enableMajorityReadConcern [=arg(=1)] (=1) Enables majority readConcern Sharding options: --configsvr Declare this is a config db of a cluster; default port 27019; default dir /data/configdb --shardsvr Declare this is a shard db of a cluster; default port 27018 Storage options: --storageEngine arg What storage engine to use - defaults to wiredTiger if no data files present --dbpath arg Directory for datafiles - defaults to \data\db\ which is D:\data\db\ based on the current working drive --directoryperdb Each database will be stored in a separate directory --syncdelay arg (=60) Seconds between disk syncs (0=never, but not recommended) --journalCommitInterval arg (=100) how often to group/batch commit (ms) --noIndexBuildRetry Do not retry any index builds that were interrupted by shutdown --upgrade Upgrade db if needed --repair Run repair on all dbs --journal Enable journaling --nojournal Disable journaling (journaling is on by default for 64 bit) Free Monitoring Options: --enableFreeMonitoring arg Enable Cloud Free Monitoring (on|runtime|off) --freeMonitoringTag arg Cloud Free Monitoring Tags WiredTiger options: --wiredTigerCacheSizeGB arg Maximum amount of memory to allocate for cache; Defaults to 1/2 of physical RAM --wiredTigerJournalCompressor arg (=snappy) Use a compressor for log records [none|snappy|zlib|zstd] --wiredTigerDirectoryForIndexes Put indexes and data in different directories --wiredTigerMaxCacheOverflowFileSizeGB arg (=0) Maximum amount of disk space to use for cache overflow; Defaults to 0 (unbounded) --wiredTigerCollectionBlockCompressor arg (=snappy) Block compression algorithm for collection data [none|snappy|zlib|zstd] --wiredTigerIndexPrefixCompression arg (=1) Use prefix compression on row-store leaf pages TLS Options: --tlsOnNormalPorts Use TLS on configured ports --tlsMode arg Set the TLS operation mode (disabled|allowTLS|preferTLS|requireTLS ) --tlsCertificateKeyFile arg Certificate and key file for TLS --tlsCertificateKeyFilePassword arg Password to unlock key in the TLS certificate key file --tlsClusterFile arg Key file for internal TLS authentication --tlsClusterPassword arg Internal authentication key file password --tlsCAFile arg Certificate Authority file for TLS --tlsClusterCAFile arg CA used for verifying remotes during inbound connections --tlsCRLFile arg Certificate Revocation List file for TLS --tlsDisabledProtocols arg Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2] --tlsAllowConnectionsWithoutCertificates Allow client to connect without presenting a certificate --tlsAllowInvalidHostnames Allow server certificates to provide non-matching hostnames --tlsAllowInvalidCertificates Allow connections to servers with invalid certificates --tlsFIPSMode Activate FIPS 140-2 mode at startup --tlsCertificateSelector arg TLS Certificate in system store --tlsClusterCertificateSelector arg SSL/TLS Certificate in system store for internal TLS authentication --tlsLogVersions arg Comma separated list of TLS protocols to log on connect [TLS1_0,TLS1_1,TLS1_2 ] Windows Service Control Manager options: --install Install Windows service --remove Remove Windows service --reinstall Reinstall Windows service (equivalent to --remove followed by --install) --serviceName arg Windows service name --serviceDisplayName arg Windows service display name --serviceDescription arg Windows service description --serviceUser arg Account for service execution --servicePassword arg Password used to authenticate serviceUser D:\MongoDB\Server\4.2\bin>net stop MongoDB MongoDB Server (MongoDB) 服務已成功停止。 D:\MongoDB\Server\4.2\bin>net start MongoDB MongoDB Server (MongoDB) 服務正在啟動 .. MongoDB Server (MongoDB) 服務已經啟動成功。 D:\MongoDB\Server\4.2\bin>mongo MongoDB shell version v4.2.6 connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID("c14b3b14-14e6-4f45-85d1-0a209ac99ac0") } MongoDB server version: 4.2.6 Server has startup warnings: 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2020-04-24T17:35:16.580+0800 I CONTROL [initandlisten] --- Enable MongoDB's free cloud-based monitoring service, which will then receive and display metrics about your deployment (disk utilization, CPU, operation statistics, etc). The monitoring data will be available on a MongoDB website with a unique URL accessible to you and anyone you share the URL with. MongoDB may use this information to make product improvements and to suggest MongoDB products and deployment options to you. To enable free monitoring, run the following command: db.enableFreeMonitoring() To permanently disable this reminder, run the following command: db.disableFreeMonitoring() --- > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users > use admin switched to db admin > show users { "_id" : "admin.admin", "userId" : UUID("ee717096-e66e-4554-95a5-29aafd999c86"), "user" : "admin", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use admin switched to db admin > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users > db.user.find() { "_id" : ObjectId("5ea2a7feaf59424af80005c6"), "id" : 1, "user_name" : "pzj", "note" : "用戶pzj", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會員" } } { "_id" : ObjectId("5ea2a87daf59424af80005c7"), "id" : 2, "user_name" : "pzj1", "note" : "用戶pzj1", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會員" } } { "_id" : ObjectId("5ea2a898af59424af80005c8"), "id" : 3, "user_name" : "pzj3", "note" : "用戶pzj3", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會員" } } { "_id" : ObjectId("5ea2a89eaf59424af80005c9"), "id" : 4, "user_name" : "pzj4", "note" : "用戶pzj4", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會員" } } > db.createUser( ... ... { ... ... user : "springboot", ... ... pwd : "123456", ... ... roles: [ { role : "readWrite", db : "springboot" }] ... ... } ... ... ) Successfully added user: { "user" : "springboot", "roles" : [ { "role" : "readWrite", "db" : "springboot" } ] } > use admin switched to db admin > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users { "_id" : "springboot.springboot", "userId" : UUID("da61542e-0c24-49b1-aa36-378580a2627a"), "user" : "springboot", "db" : "springboot", "roles" : [ { "role" : "readWrite", "db" : "springboot" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > show user 2020-04-24T21:16:27.933+0800 E QUERY [js] uncaught exception: Error: don't know how to show [user] : shellHelper.show@src/mongo/shell/utils.js:1139:11 shellHelper@src/mongo/shell/utils.js:790:15 @(shellhelp2):1:1 > show dbs admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use springboot switched to db springboot > show users { "_id" : "springboot.springboot", "userId" : UUID("da61542e-0c24-49b1-aa36-378580a2627a"), "user" : "springboot", "db" : "springboot", "roles" : [ { "role" : "readWrite", "db" : "springboot" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } > springboot.user 2020-04-24T21:16:57.022+0800 E QUERY [js] uncaught exception: ReferenceError: springboot is not defined : @(shell):1:1 > db.user.findOne({id:1}) { "_id" : ObjectId("5ea2a7feaf59424af80005c6"), "id" : 1, "user_name" : "pzj", "note" : "用戶pzj", "role" : { "_id" : "5ea2a639af59424af80005c5", "id" : 3, "role_name" : "vip_user", "note" : "會員" } } > show dbs; admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB > use xx switched to db xx > show dbs; admin 0.000GB config 0.000GB local 0.000GB springboot 0.000GB >
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot整合MyBatis-Plus3.1教程詳解
這篇文章主要介紹了SpringBoot整合MyBatis-Plus3.1詳細教程,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08IDEA2020.1使用LeetCode插件運行并調試本地樣例的方法詳解
這篇文章主要介紹了IDEA2020.1使用LeetCode插件運行并調試本地樣例的方法,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-09-09mybatis自定義參數(shù)類型轉換器數(shù)據庫字段加密脫敏
這篇文章主要為大家介紹了mybatis自定義參數(shù)類型轉換器數(shù)據庫字段加密脫敏,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09