1、java连接MongoDB(通过客户端api的方式)进行操作
现在 MongoClient mongoClient = new MongoClient(addrs,credentials); 方式已经删除了,不再用了,所以下面的连接方式有三种
(1)连接
方式一
MongoClientOptions.Builder builder = MongoClientOptions.builder(); //可以通过builder做各种详细配置
MongoClientOptions myOptions = builder.build();
ArrayList<ServerAddress> serverAddressList = new ArrayList();
ServerAddress record = new ServerAddress("localhost", 27017); //IP、端口
serverAddressList.add(record);
//用户名、默认库名、密码
MongoCredential credential = MongoCredential.createCredential("账号", "默认库名", "密码".toCharArray());
MongoClient mongoClient = new MongoClient(serverAddressList, credential, myOptions);
这的默认库名一般是admin,看你自己的设置了
方式二
String sURI = String.format("mongodb://%s:%s@%s:%d/%s", "账号", "密码", "localhost", 27017, "默认库名");
MongoClient mongoClient = new MongoClient(new MongoClientURI(sURI));
采用的是URI的方式最后那个是默认库
方式三
//不使用用户名和密码直接进行登陆
MongoClient mongoClient = new MongoClient("localhost", 27017);
这个非常简单,实际中不可能这么干,也就刚开始学习时这个干
(2)操作(这里用第一种连接方式)
1、数据库连接
static MongoDatabase mongoDatabase=null;
private static void connectMongoDB() {
try {
//第一种方式
MongoClientOptions.Builder builder = MongoClientOptions.builder(); //可以通过builder做各种详细配置
MongoClientOptions myOptions = builder.build();
ArrayList<ServerAddress> serverAddressList = new ArrayList();
ServerAddress record = new ServerAddress("localhost", 27017); //IP、端口
serverAddressList.add(record);
//用户名、默认库名、密码
MongoCredential credential = MongoCredential.createCredential("user", "admin", "123456".toCharArray());
MongoClient mongoClient = new MongoClient(serverAddressList, credential, myOptions);
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
2、创建集合
//创建集合
private static void createCollection() {
try {
mongoDatabase.createCollection("新的集合");
System.out.println("集合创建成功");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
3、搜索文档
//搜索文档
private static void queryDocument() {
try {
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功");
// 检索所有文档
/**
* 1. 获取迭代器FindIterable<Document> 2. 获取游标MongoCursor<Document> 3.
* 通过游标遍历检索出的文档集合
*/
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
3、删除文档
private static void deleteDoc() {
try {
MongoCollection<Document> collection = mongoDatabase.getCollection("five");
System.out.println("集合 three 选择成功");
//删除符合条件(title)的第一个文档
collection.deleteOne(Filters.eq("name", "sss"));
// 删除所有符合条件的文档
// collection.deleteMany(Filters.eq("likes", 200));
// 检索查看结果
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
删除文档这需要注意一点,我遇到的就是:删除的文档是否是在固定集合里,否则会报异常
com.mongodb.MongoWriteException: cannot remove from a capped collection
关于固定集合可以看这固定集合的定义作用和注意事项 这就说一点:不可以对固定集合执行删除文档操作,但可以删除整个集合。
4、修改文档
//修改文档
private static void updateDocument() {
try {
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功");
// 更新文档 将文档中likes=100的文档修改为likes=200
collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200)));
// 检索查看结果
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
5、插入文档
//插入文档
private static void insertDoc() {
try {
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功");
// 插入文档
/**
* 1. 创建文档 org.bson.Document 参数为key-value的格式 2. 创建文档集合List
* <Document> 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List
* <Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
* 下面就是插入文档的格式
*/
Document document = new Document("title", "MongoDB").append("description", "database").append("likes", 100)
.append("by", "Fly");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);
System.out.println("文档插入成功");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
6、创建集合
private static void createCollection() {
try {
mongoDatabase.createCollection("新的集合");
System.out.println("集合创建成功");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
执行
public static void main(String[] args) {
connectMongoDB();
deleteDoc();
}
关于获得指定集合的,如果不能确定只需要某个数据库的某个集合,那就按上面的,数据库连接到库就行,至于连接哪个表就由方法自己决定吧
SSM整合MongoDB
1、依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.22.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.2</version>
</dependency>
注意:在导依赖的时候一定要注意版本,Spring 4.x的spring-data-mongodb 的版本一定是1.x ,版本不一致会报错
org.springframework.util.Assert.isInstanceOf(Ljava/lang/Class;Ljava/lang/Object;Ljava/util/function/Supplier;)V
2、目录结构
3、User(javaBean)
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "book") //这个是注解,表示这个bean对应的哪个集合(哪张表)
public class User {
@Id //这个注解代表的是文档中MoongoDB生成的Id
private String id;
@Field("userName") //代表这个对应着文档里哪个字段
private String userName;
@Field("userPhone")
private String userPhone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
}
原本想加上
@Indexed(expireAfterSeconds = 30)
private Date expireTime;
添加时间限制,意思是存在30s,30秒后此文档会被删除
没弄出来,到时间它一样不结束,我也没办法了,就不加上了
如果有谁知道原因或成功了,请评论告诉我一声
4、mongoDB层
接口
public interface MongoDao {
/**
* show 插入文档
*
* */
void insert(User user);
/**
* show 根据Id删除文档,别的也行
* */
void deleteByUserName(User user);
/**
* show 修改文档的字段的内容
* */
void updateByUserName(User user);
/**
* show 查询文档
* */
List<User> selectUsers();
}
实现类
@Repository("mongoDao")
public class MongoDaoImpl implements MongoDao {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public void insert(User user) {
mongoTemplate.insert(user);
}
@Override
public void deleteByUserName(User user) {
Query query=new Query(Criteria.where("userName").is(user.getUserName()));
mongoTemplate.remove(query,User.class);
}
@Override
public void updateByUserName(User user) {
Query query=new Query(Criteria.where("userName").is("万一"));
Update update= new Update().set("userName", user.getUserName()).set("userPhone", user.getUserPhone());
//更新查询返回结果集的第一条
mongoTemplate.updateFirst(query,update,User.class);
//更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,User.class);
}
@Override
public List<User> selectUsers() {
//条件,例如userName = 万一,相当于关系型数据的where
Query query=new Query(Criteria.where("userName").is("万一"));
//根据条件查询单个
// User user = mongoTemplate.findOne(query , User.class);
// 根据条件查询多个
List<User> users = mongoTemplate.find(query,User.class);
// 查询全部
// List<User> users = mongoTemplate.findAll(User.class);
return users;
}
}
5、service层
接口
public interface UserService {
void insert(User user);
void deleteByUserName(User user);
void updateByUserName(User user);
List<User> select();
}
实现类
@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired
private MongoDao mongoDao;
@Override
public void insert(User user) {
mongoDao.insert(user);
}
@Override
public void deleteByUserName(User user) {
mongoDao.deleteByUserName(user);
}
@Override
public void updateByUserName(User user) {
mongoDao.updateByUserName(user);
}
@Override
public List<User> select() {
return mongoDao.selectUsers();
}
}
6、mongoDB的配置文件
#DB name //这个解释一下,因为登录时需要要验证,这个就好比命令行登录时最后填的数据库名
mongo.dbname = admin
#mu biao DB //上面和这个形成对比,这个是你想去哪个数据库中找指定的集合,前提是你有那个数据库的权限
mongo.target = user
#username
mongo.username =root
#password
mongo.password =123456
#host
mongo.host = 127.0.0.1
#port
mongo.port = 27017
#xiancheng zui da zu se shu
mongo.connectionsPerHost= 8
#xiancheng dui lie shu
mongo.threadsAllowedToBlockForConnectionMultiplier= 4
#connectTimeout ms
mongo.connectTimeout= 1500
#maxWaitTime
mongo.maxWaitTime= 1500
#autoConnect
mongo.autoConnectRetry= true
#socketKeepAlive
mongo.socketKeepAlive= true
#socketTimeout
mongo.socketTimeout=1500
#du xie fen li
mongo.slaveOk=true
7、spring-mongoDB.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 包扫描 -->
<context:component-scan base-package="mongoDB"/>
<!--引入MongoDB连接文件-->
<context:property-placeholder location="classpath:mongodb.properties" ignore-unresolvable="true"/>
<!--连接MongoDB服务器-->
<mongo:mongo-client id="mongo" host="${mongo.host}" port="${mongo.port}"
credentials="${mongo.username}:${mongo.password}@${mongo.dbname}">
<mongo:client-options connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"/>
</mongo:mongo-client>
<!-- 设置自己想去哪个数据库 -->
<mongo:db-factory id="mongoDbFactory" dbname="${mongo.target}" mongo-ref="mongo"/>
<!-- 去掉_class字段配置 -->
<bean id="mappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey"><null/></constructor-arg>
</bean>
<bean id="mappingMongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean>
<!--配置mongoTemplate模板-->
<!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成-->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
<!--把去掉_class字段的加入到模板中去-->
<constructor-arg ref="mappingMongoConverter"/>
</bean>
</beans>
这里注意三点:
- 引入mongoDB的配置文件别忘了加ignore-unresolvable="true"
- 如果是通过验证登录的请加上
credentials=\"${mongo.username}:\${mongo.password}@${mongo.dbname}"
否则可以不加 - _class字段的配置如果需要就添加上,不需要就可以不添加,添加上去的后果就是文档新开了一个字段名为 _class,类型为String,记录此条数据是来自哪个bean的相对路径,
8、spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
">
<!-- 包扫描 -->
<context:component-scan base-package="service"/>
<import resource="spring-mongoDB.xml"/>
</beans>
mongodb能支持事务,但是影响写入性能,不建议使用。换句话说,要用事务考虑用关系型数据库。
9、测试类
@Autowired
private ApplicationContext ctx = null;
@Autowired
private UserService userService = null;
@Test
public void insert() {
ctx = new ClassPathXmlApplicationContext("spring-service.xml");
userService = ctx.getBean(UserService.class);
User user = new User();
user.setUserName("乔峰");
user.setUserPhone("254****5555");
userService.insert(user);
};
@Test
public void select() {
ctx = new ClassPathXmlApplicationContext("spring-service.xml");
userService = ctx.getBean(UserService.class);
List<User> list = userService.select();
for(User user:list) {
System.out.println(user.toString());
}
}
@Test
public void update() {
ctx = new ClassPathXmlApplicationContext("spring-service.xml");
userService = ctx.getBean(UserService.class);
User user = new User();
user.setUserName("李华");
user.setUserPhone("7875**5544");
userService.updateByUserName(user);
}
@Test
public void delete() {
ctx = new ClassPathXmlApplicationContext("spring-service.xml");
userService = ctx.getBean(UserService.class);
User user = new User();
user.setUserName("李华");
user.setUserPhone("7875**5544");
userService.deleteByUserName(user);
}
还有一个好很重要的分页怎么能忘了呢?
//查找
//分页查询
Query query = new Query();
query.skip("跳过的数据条数").limit("一页数据有多少条数");
return mongoTemplate.find(query, User.class);
上面只实现了简单增删查改和分页,还有很多深的没有写出来,到时候用到哪个再写吧
这段时间磕磕碰碰,断断续续,各种事情拖延脚步,到现在MongoDB总算可以告一段落了