1.创建工程,引入坐标
<dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.1.8.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.6.RELEASE</version> </dependency> </dependencies>
2.创建配置文件applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd"> <mongo:repositories base-package="com.fgy.dao"></mongo:repositories> <!-- spring连接mongodb数据库的配置 --> <mongo:mongo-client host="192.168.43.182" port="27017" id="mongo"> <!-- Spring在插入数据库时没有返回状态配置:write-concern获取异常 WriteConcern.NONE:没有异常抛出 WriteConcern.NORMAL:仅抛出网络错误异常,没有服务器错误异常 WriteConcern.SAFE:抛出网络错误异常、服务器错误异常;并等待服务器完成写操作。 WriteConcern.MAJORITY: 抛出网络错误异常、服务器错误异常;并等待一个主服务器完成写操作。 WriteConcern.FSYNC_SAFE: 抛出网络错误异常、服务器错误异常;写操作等待服务器将数据刷新到磁盘。 WriteConcern.JOURNAL_SAFE:抛出网络错误异常、服务器错误异常;写操作等待服务器提交到磁盘的日志文件。 WriteConcern.REPLICAS_SAFE:抛出网络错误异常、服务器错误异常;等待至少2台服务器完成写操作。 --> <mongo:client-options write-concern="SAFE"/> </mongo:mongo-client> <mongo:db-factory id="mongoDbFactory" dbname="articledb" mongo-ref="mongo"/> <!--mongoTemplate--> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> </beans>
3.创建实体类
// @Document(collection = "article") @Document("article") public class Article { @Id private Integer id; @Field("title") // 给映射存储到 mongodb 的字段取别名 private String title; private String content; private Integer hits; /*********** get/set方法 ***********/ }
4.自定义 dao接口
// 自定义dao接口继承MongoRepository<实体类型,主键类型> public interface ArticleDao extends MongoRepository<Article, Integer> { }
5.测试
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class ArticleDaoTest { @Autowired private ArticleDao articleDao; @Test public void testSave() { Article article = new Article(); article.setId(1); article.setTitle("java入门到精通"); article.setContent("趁现在还年轻,转行吧!"); article.setHits(100); articleDao.save(article); } }