1. 程式人生 > >spring boot整合mongodb最簡單版

spring boot整合mongodb最簡單版

作者:flystarfly

通過spring tools suite新建一個spring project。帶maven的即可

pom.xml檔案配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples</groupId>
  <artifactId>springbootmongodb</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <name>springbootmongodb</name>
  <url>http://maven.apache.org</url>
	  <properties>
		<!-- Generic properties -->
		<java.version>1.7</java.version> java版本號,根據自己情況來
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<!-- Spring -->
		<spring-framework.version>4.2.3.RELEASE</spring-framework.version> 這裡版本要高
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<!-- Hibernate / JPA -->
		<hibernate.version>4.2.1.Final</hibernate.version>  //預設生成了,沒啥用
		<!-- Logging -->
		<logback.version>1.0.13</logback.version>
		<slf4j.version>1.7.5</slf4j.version>
		<!-- Test -->
		<junit.version>4.11</junit.version>
	</properties>

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
    </parent>

	<dependencies>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

		<!-- Logging with SLF4J & LogBack -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
			<scope>runtime</scope>
		</dependency>

		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		
		<!-- Spring boot -->
		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
               <exclusions>
		        	<exclusion>
		            	<groupId>org.springframework.boot</groupId>
		            	<artifactId>spring-boot-starter-tomcat</artifactId>
		        	</exclusion>
   			 </exclusions>
        </dependency>
 <!--  spring-boot-starter-actuator依賴會引入一組基本的Spring專案,從而實現應用的快速配置和即時可用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        
        <dependency>
    		<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-tomcat</artifactId>
    			<scope>provided</scope>
		</dependency>
		
		
    	
    	 <!-- 增加mongodb支援 -->
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	

		
		<!-- Test Artifacts -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring-framework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>

	</dependencies>	

新建實體類 SysUser

 
package entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class SysUser  {
	//mongodb需要指定ID
	 @Id
	private long seqid;
	
	private String name;

	private String password;
	
	private long roleId;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public long getRoleId() {
		return roleId;
	}
	public void setRoleId(long roleId) {
		this.roleId = roleId;
	}

	public long getSeqid() {
		return seqid;
	}
	public void setSeqid(long seqid) {
		this.seqid = seqid;
	}

}

建立介面SysUserRepository extends MongoRepository

package mapper;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import entity.SysUser;

@Component
public interface SysUserRepository extends MongoRepository {
	SysUser findByName(String name); //自定義的方法
}

建立service類,寫業務邏輯方法

SysUserService
package service;
import java.util.List;
import mapper.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import entity.SysUser;

@Service
@EnableMongoRepositories(basePackages="mapper" ) //掃描指定目錄下面的MongoRepositories介面
public class SysUserService{

	@Autowired
   private SysUserRepository sysUserRepository;
   
    @RequestMapping("save")
    public  String save(){
    	SysUser sysUser = new SysUser();
    	sysUser.setName("張三");
    	sysUser.setPassword("123456");
    	sysUser.setSeqid(1L);
    	sysUserRepository.save(sysUser);
      
       sysUser = new SysUser();
       sysUser.setName("李四");
       sysUser.setPassword("123456");
       sysUser.setSeqid(2L);
       sysUserRepository.save(sysUser);
      
       return "ok";
    }
   
    @RequestMapping("find")
    public List find(){
       return sysUserRepository.findAll();
    }
   
    @RequestMapping("findByName")
    public SysUser findByName(){
       return sysUserRepository.findByName("張三");
    }
	
}

最後是控制器

package controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import service.SysUserService;


import entity.SysUser;
/**
 * Created by wenchao.ren on 2014/4/26.
 */
@SpringBootApplication  
//啟註解事務管理  
@Controller
@Import (SysUserService.class )
public class SimpleController {

	@Autowired
	private SysUserService sysUserService;

	@RequestMapping(value ="/hello", method = RequestMethod.GET)
    @ResponseBody
    public String hello(){
		SysUser sysUser = new SysUser();
		sysUserService.save();
		SysUser sysUser2= sysUserService.findByName();
        return sysUser2.getName();
    }
 
   public static void main(String[] args) {
        SpringApplication.run(SimpleController.class, args);
    }
    
}

還有applicationContext.properties

# mongodb note:mongo3.x will not use host and port,only use uri
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.uri=mongodb://localhost:27017/springbootdb
server.port=8011