Spring整合MongoDB

释放双眼,带上耳机,听听看~!

spring整合MongoDB

4.1 创建maven项目

Spring整合MongoDB

4.1.1 repositories

创建maven项目,其中repositories使用spring的maven库:

 

Java代码  

<repositories>  
1.
    <repository>  
1.
        <id>central</id>  
1.
        <name>Maven Central</name>  
1.
        <url>http:
//repo1.maven.org/maven2/</url>  
1.
    </repository>  
1.
    <repository>  
1.
        <id>spring-release</id>  
1.
        <name>Spring Maven Release Repository</name>  
1.
        <url>http:
//repo.springsource.org/libs-release</url>  
1.
    </repository>  
1.
    <repository>  
1.
        <id>atlassian-m2-repository</id>  
1.
        <url>https:
//m2proxy.atlassian.com/repository/public</url>  
1.
    </repository>  
1.
</repositories>  

 

4.1.2 Dependencies

使用到的jar包:

 

Java代码  

<dependencies>  
1.
    <dependency>  
1.
        <groupId>javax.servlet</groupId>  
1.
        <artifactId>servlet-api</artifactId>  
1.
        <version>
2.5</version>  
1.
        <type>jar</type>  
1.
        <scope>provided</scope>  
1.
    </dependency>  
1.
    <dependency>  
1.
        <groupId>org.slf4j</groupId>  
1.
        <artifactId>slf4j-api</artifactId>  
1.
        <version>
1.6.
1</version>  
1.
        <type>jar</type>  
1.
        <scope>compile</scope>  
1.
    </dependency>  
1.
    <dependency>  
1.
        <groupId>org.slf4j</groupId>  
1.
        <artifactId>slf4j-log4j12</artifactId>  
1.
        <version>
1.7.
5</version>  
1.
        <type>jar</type>  
1.
        <scope>runtime</scope>  
1.
    </dependency>  
1.
    <dependency>  
1.
        <groupId>org.mongodb</groupId>  
1.
        <artifactId>mongo-java-driver</artifactId>  
1.
        <version>
2.10.
1</version>  
1.
        <type>jar</type>  
1.
        <scope>compile</scope>  
1.
    </dependency>  
1.
    <dependency>  
1.
        <groupId>org.springframework.data</groupId>  
1.
        <artifactId>spring-data-mongodb</artifactId>  
1.
        <version>
1.2.
1.RELEASE</version>  
1.
        <type>jar</type>  
1.
        <scope>compile</scope>  
1.
    </dependency>  
1.
    <dependency>  
1.
        <groupId>org.springframework.data</groupId>  
1.
        <artifactId>spring-data-mongodb-cross-store</artifactId>  
1.
        <version>
1.2.
1.RELEASE</version>  
1.
        <type>jar</type>  
1.
        <scope>compile</scope>  
1.
    </dependency>  
1.
    <dependency>  
1.
        <groupId>org.springframework.data</groupId>  
1.
        <artifactId>spring-data-mongodb-log4j</artifactId>  
1.
        <version>
1.2.
1.RELEASE</version>  
1.
        <type>jar</type>  
1.
        <scope>compile</scope>  
1.
    </dependency>  
1.
</dependencies>  

 

 

4.2 添加spring配置文件

spring的配置文件applicationContext.xml

 

Java代码  

<?xml version=
"1.0" encoding=
"UTF-8"?>  

<beans xmlns=
"http://www.springframework.org/schema/beans"  
1.
    xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"   
1.
    xmlns:context=
"http://www.springframework.org/schema/context"  
1.
    xmlns:mongo=
"http://www.springframework.org/schema/data/mongo"  
1.
    xsi:schemaLocation="http:
//www.springframework.org/schema/beans  
1.
        http:
//www.springframework.org/schema/beans/spring-beans-3.0.xsd  
1.
        http:
//www.springframework.org/schema/data/mongo       
1.
        http:
//www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd   
1.
        http:
//www.springframework.org/schema/context  
1.
        http:
//www.springframework.org/schema/context/spring-context-3.0.xsd">  
1.
  
1.
    <context:component-scan base-
package=
"liming.mongodb.example" />  
1.
  
1.
    <mongo:mongo host=
"127.0.0.1" port=
"27017" />  
1.
  
1.
    <!– mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 –>  
1.
    <mongo:db-factory dbname=
"student" mongo-ref=
"mongo" />  
1.
  
1.
    <!– mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 –>  
1.
    <bean id=
"mongoTemplate" 
class=
"org.springframework.data.mongodb.core.MongoTemplate">  
1.
        <constructor-arg name=
"mongoDbFactory" ref=
"mongoDbFactory" />  
1.
    </bean>  
1.
  
1.
    <!– 映射转换器,扫描back-
package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 –>  
1.
    <mongo:mapping-converter base-
package=
"climing.mongodb.example.data.model" />  
1.
  
1.
    <!– mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 –>  
1.
    <mongo:repositories base-
package=
"liming.mongodb.example.data.impl" />  
1.
  
1.
    context:annotation-config /  
1.
  
1.
</beans>  

 

 

 

4.3 增删改查

Userl实现的增删改查:

4.3.1UserEntity

 

Java代码  

package liming.mongodb.example.data.model;  
1.
  
1.
import java.util.Date;  
1.
  
1.
import org.springframework.data.annotation.Id;  
1.
import org.springframework.data.mongodb.core.mapping.Document;  
1.
  
1.
@Document(collection = 
"user")  
1.
public 
class UserEntity {  
1.
  
1.
    
@Id  
1.
    
private String id;  
1.
    
private NameEntity name;  
1.
    
private 
int age;  
1.
    
private 
int works;  
1.
    
private Date birth;  
1.
    
private String password;  
1.
    
private String regionName;  
1.
    
private String[] special;  
1.
  
1.
    
public String getId() {  
1.
        
return id;  
1.
    }  
1.
  
1.
    
public 
void setId(String id) {  
1.
        
this.id = id;  
1.
    }  
1.
  
1.
    
public NameEntity getName() {  
1.
        
return name;  
1.
    }  
1.
  
1.
    
public 
void setName(NameEntity name) {  
1.
        
this.name = name;  
1.
    }  
1.
  
1.
    
public 
int getAge() {  
1.
        
return age;  
1.
    }  
1.
  
1.
    
public 
void setAge(
int age) {  
1.
        
this.age = age;  
1.
    }  
1.
  
1.
    
public 
int getWorks() {  
1.
        
return works;  
1.
    }  
1.
  
1.
    
public 
void setWorks(
int works) {  
1.
        
this.works = works;  
1.
    }  
1.
  
1.
    
public Date getBirth() {  
1.
        
return birth;  
1.
    }  
1.
  
1.
    
public 
void setBirth(Date birth) {  
1.
        
this.birth = birth;  
1.
    }  
1.
  
1.
    
public String getPassword() {  
1.
        
return password;  
1.
    }  
1.
  
1.
    
public 
void setPassword(String password) {  
1.
        
this.password = password;  
1.
    }  
1.
  
1.
    
public String getRegionName() {  
1.
        
return regionName;  
1.
    }  
1.
  
1.
    
public 
void setRegionName(String regionName) {  
1.
        
this.regionName = regionName;  
1.
    }  
1.
  
1.
    
public String[] getSpecial() {  
1.
        
return special;  
1.
    }  
1.
  
1.
    
public 
void setSpecial(String[] special) {  
1.
        
this.special = special;  
1.
    }  
1.
  
1.
}  

 

 

4.3.2 NameEntity

 

Java代码  

package liming.mongodb.example.data.model;  
1.
  
1.
public 
class NameEntity {  
1.
  
1.
    
private String username;  
1.
  
1.
    
private String nickname;  
1.
  
1.
    
public String getUsername() {  
1.
        
return username;  
1.
    }  
1.
  
1.
    
public 
void setUsername(String username) {  
1.
        
this.username = username;  
1.
    }  
1.
  
1.
    
public String getNickname() {  
1.
        
return nickname;  
1.
    }  
1.
  
1.
    
public 
void setNickname(String nickname) {  
1.
        
this.nickname = nickname;  
1.
    }  
1.
  
1.
}  

 

 

4.3.3 UserDao

 

Java代码  

package liming.mongodb.example.data;  
1.
  
1.
import java.util.List;  
1.
  
1.
import liming.mongodb.example.data.model.UserEntity;  
1.
  
1.
import org.springframework.transaction.annotation.Transactional;  
1.
  
1.
@Transactional  
1.
public 
interface UserDao {  
1.
  
1.
    
public 
abstract 
void _test();  
1.
  
1.
    
public 
abstract 
void createCollection();  
1.
  
1.
    
public 
abstract List<UserEntity> findList(
int skip, 
int limit);  
1.
  
1.
    
public 
abstract List<UserEntity> findListByAge(
int age);  
1.
  
1.
    
public 
abstract UserEntity findOne(String id);  
1.
  
1.
    
public 
abstract UserEntity findOneByUsername(String username);  
1.
  
1.
    
public 
abstract 
void insert(UserEntity entity);  
1.
  
1.
    
public 
abstract 
void update(UserEntity entity);  
1.
  
1.
}  

 

 

4.3.4 UserDaoImpl

 

Java代码  

package liming.mongodb.example.data.impl;  
1.
  
1.
import java.util.List;  
1.
import java.util.Set;  
1.
  
1.
import liming.mongodb.example.data.UserDao;  
1.
import liming.mongodb.example.data.model.UserEntity;  
1.
  
1.
import org.slf4j.Logger;  
1.
import org.slf4j.LoggerFactory;  
1.
import org.springframework.beans.factory.annotation.Autowired;  
1.
import org.springframework.data.domain.Sort;  
1.
import org.springframework.data.domain.Sort.Direction;  
1.
import org.springframework.data.domain.Sort.Order;  
1.
import org.springframework.data.mongodb.core.MongoTemplate;  
1.
import org.springframework.data.mongodb.core.query.Criteria;  
1.
import org.springframework.data.mongodb.core.query.Query;  
1.
import org.springframework.data.mongodb.core.query.Update;  
1.
import org.springframework.stereotype.Repository;  
1.
  
1.
import com.mongodb.DB;  
1.
  
1.
@Repository  
1.
public 
class UserDaoImpl 
implements UserDao {  
1.
  
1.
    
public 
static 
final Logger logger = LoggerFactory.getLogger(UserDaoImpl.
class);  
1.
  
1.
    
@Autowired  
1.
    
private MongoTemplate mongoTemplate;  
1.
  
1.
    
@Override  
1.
    
public 
void _test() {  
1.
        Set<String> colls = 
this.mongoTemplate.getCollectionNames();  
1.
        
for (String coll : colls) {  
1.
            logger.info(
"CollectionName=" + coll);  
1.
        }  
1.
        DB db = 
this.mongoTemplate.getDb();  
1.
        logger.info(
"db=" + db.toString());  
1.
    }  
1.
  
1.
    
@Override  
1.
    
public 
void createCollection() {  
1.
        
if (!
this.mongoTemplate.collectionExists(UserEntity.
class)) {  
1.
            
this.mongoTemplate.createCollection(UserEntity.
class);  
1.
        }  
1.
    }  
1.
  
1.
    
@Override  
1.
    
public List<UserEntity> findList(
int skip, 
int limit) {  
1.
        Query query = 
new Query();  
1.
        query.with(
new Sort(
new Order(Direction.ASC, 
"_id")));  
1.
        query.skip(skip).limit(limit);  
1.
        
return 
this.mongoTemplate.find(query, UserEntity.
class);  
1.
    }  
1.
  
1.
    
@Override  
1.
    
public List<UserEntity> findListByAge(
int age) {  
1.
        Query query = 
new Query();  
1.
        query.addCriteria(
new Criteria(
"age").is(age));  
1.
        
return 
this.mongoTemplate.find(query, UserEntity.
class);  
1.
    }  
1.
  
1.
    
@Override  
1.
    
public UserEntity findOne(String id) {  
1.
        Query query = 
new Query();  
1.
        query.addCriteria(
new Criteria(
"_id").is(id));  
1.
        
return 
this.mongoTemplate.findOne(query, UserEntity.
class);  
1.
    }  
1.
  
1.
    
@Override  
1.
    
public UserEntity findOneByUsername(String username) {  
1.
        Query query = 
new Query();  
1.
        query.addCriteria(
new Criteria(
"name.username").is(username));  
1.
        
return 
this.mongoTemplate.findOne(query, UserEntity.
class);  
1.
    }  
1.
  
1.
    
@Override  
1.
    
public 
void insert(UserEntity entity) {  
1.
        
this.mongoTemplate.insert(entity);  
1.
  
1.
    }  
1.
  
1.
    
@Override  
1.
    
public 
void update(UserEntity entity) {  
1.
        Query query = 
new Query();  
1.
        query.addCriteria(
new Criteria(
"_id").is(entity.getId()));  
1.
        Update update = 
new Update();  
1.
        update.set(
"age", entity.getAge());  
1.
        update.set(
"password", entity.getPassword());  
1.
        update.set(
"regionName", entity.getRegionName());  
1.
        update.set(
"special", entity.getSpecial());  
1.
        update.set(
"works", entity.getWorks());  
1.
        update.set(
"name", entity.getName());  
1.
        
this.mongoTemplate.updateFirst(query, update, UserEntity.
class);  
1.
  
1.
    }  
1.
  
1.
}  

 

 

4.3.5 测试代码

 

Java代码  

package liming.mongodb.example;  
1.
  
1.
import java.util.Arrays;  
1.
import java.util.Date;  
1.
import java.util.List;  
1.
  
1.
import liming.mongodb.example.data.UserDao;  
1.
import liming.mongodb.example.data.impl.UserDaoImpl;  
1.
import liming.mongodb.example.data.model.UserEntity;  
1.
  
1.
import org.springframework.context.ConfigurableApplicationContext;  
1.
import org.springframework.context.support.ClassPathXmlApplicationContext;  
1.
  
1.
public 
class ApplicationSpring {  
1.
  
1.
    
public 
static 
void main(String[] args) {  
1.
  
1.
        System.out.println(
"Bootstrapping HelloMongo");  
1.
  
1.
        ConfigurableApplicationContext context = 
null;  
1.
        context = 
new ClassPathXmlApplicationContext(
"applicationContext.xml");  
1.
  
1.
        UserDao userDao = context.getBean(UserDaoImpl.
class);  
1.
            userDao._test();  
1.
        UserEntity entity1 = 
new UserEntity();  
1.
        entity1.setId(
"5");  
1.
        entity1.setAge(
1);  
1.
        entity1.setBirth(
new Date());  
1.
        entity1.setPassword(
"asdfasdf");  
1.
        entity1.setRegionName(
"北京");  
1.
        entity1.setWorks(
1);  
1.
        userDao.insert(entity1);  
1.
        userDao.update(entity1);  
1.
        userDao.createCollection();  
1.
      
1.
        List<UserEntity> list = userDao.findList(
0, 
10);  
1.
        
for (UserEntity e : list) {  
1.
            System.out.println(
"all – id=" + e.getId() + 
", age=" + e.getAge() + 
", password=" + e.getPassword() + 
", regionName=" + e.getRegionName() + 
", special=" + Arrays.toString(e.getSpecial())  
1.
                    + 
", name=" + e.getName().getUsername() + 
"-" + e.getName().getNickname() + 
", birth=" + e.getBirth());  
1.
        }  
1.
  
1.
        list = userDao.findListByAge(
1);  
1.
        
for (UserEntity e : list) {  
1.
            System.out.println(
"age=1 – id=" + e.getId() + 
", age=" + e.getAge() + 
", password=" + e.getPassword() + 
", regionName=" + e.getRegionName() + 
", special="  
1.
                    + Arrays.toString(e.getSpecial()) + 
", name=" + e.getName().getUsername() + 
"-" + e.getName().getNickname() + 
", birth=" + e.getBirth());  
1.
        }  
1.
  
1.
        UserEntity e = userDao.findOne(
"1");  
1.
        System.out.println(
"id=1 – id=" + e.getId() + 
", age=" + e.getAge() + 
", password=" + e.getPassword() + 
", regionName=" + e.getRegionName() + 
", special=" + Arrays.toString(e.getSpecial())  
1.
                + 
", name=" + e.getName().getUsername() + 
"-" + e.getName().getNickname() + 
", birth=" + e.getBirth());  
1.
  
1.
        e = userDao.findOneByUsername(
"limingnihao");  
1.
        System.out.println(
"username=limingnihao – id=" + e.getId() + 
", age=" + e.getAge() + 
", password=" + e.getPassword() + 
", regionName=" + e.getRegionName() + 
", special="  
1.
                + Arrays.toString(e.getSpecial()) + 
", name=" + e.getName().getUsername() + 
"-" + e.getName().getNickname() + 
", birth=" + e.getBirth());  
1.
  
1.
          
1.
        System.out.println(
"DONE!");  
1.
    }  
1.
  
1.
}  

 

给TA打赏
共{{data.count}}人
人已打赏
安全运维

OpenSSH-8.7p1离线升级修复安全漏洞

2021-10-23 10:13:25

安全运维

设计模式的设计原则

2021-12-12 17:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索