http://www.ityouknow.com/springboot/2016/08/20/springboot(%E4%BA%94)-spring-data-jpa%E7%9A%84%E4%BD%BF%E7%94%A8.html
http://www.cnblogs.com/shihuc/p/5169418.html 这个不错
https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7
https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html
https://*.com/questions/44507705/spring-boot-connect-mysql-and-mongodb
同源数据库的多源支持
日常项目中因为使用的分布式开发模式,不同的服务有不同的数据源,常常需要在一个项目中使用多个数据源,因此需要配置sping data jpa对多数据源的使用,一般分一下为三步:
- 1 配置多数据源
- 2 不同源的实体类放入不同包路径
- 3 声明不同的包路径下使用不同的数据源、事务支持
这里有一篇文章写的很清楚:Spring Boot多数据源配置与使用
异构数据库多源支持
比如我们的项目中,即需要对mysql的支持,也需要对mongodb的查询等。
实体类声明@Entity
关系型数据库支持类型、声明@Document
为mongodb支持类型,不同的数据源使用不同的实体就可以了
interface PersonRepository extends Repository<Person, Long> {
…
}
@Entity
public class Person {
…
}
interface UserRepository extends Repository<User, Long> {
…
}
@Document
public class User {
…
}
但是,如果User用户既使用mysql也使用mongodb呢,也可以做混合使用
interface JpaPersonRepository extends Repository<Person, Long> {
…
}
interface MongoDBPersonRepository extends Repository<Person, Long> {
…
}
@Entity
@Document
public class Person {
…
}
也可以通过对不同的包路径进行声明,比如A包路径下使用mysql,B包路径下使用mongoDB
@EnableJpaRepositories(basePackages = "com.neo.repositories.jpa")
@EnableMongoRepositories(basePackages = "com.neo.repositories.mongo")
interface Configuration { }
http://www.jianshu.com/p/34730e595a8c
http://www.cnblogs.com/liujiduo/p/5004691.html
___________________________________
http://limingnihao.iteye.com/blog/1940446
MongoDB整合Spring
(黎明你好原创作品,转载请注明)
4.1 创建maven项目
4.1.1 repositories
创建maven项目,其中repositories使用spring的maven库:
- <repositories>
- <repository>
- <id>central</id>
- <name>Maven Central</name>
- <url>http://repo1.maven.org/maven2/</url>
- </repository>
- <repository>
- <id>spring-release</id>
- <name>Spring Maven Release Repository</name>
- <url>http://repo.springsource.org/libs-release</url>
- </repository>
- <repository>
- <id>atlassian-m2-repository</id>
- <url>https://m2proxy.atlassian.com/repository/public</url>
- </repository>
- </repositories>
4.1.2 Dependencies
使用到的jar包:
- <dependencies>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- <type>jar</type>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.6.1</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.5</version>
- <type>jar</type>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>org.mongodb</groupId>
- <artifactId>mongo-java-driver</artifactId>
- <version>2.10.1</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb</artifactId>
- <version>1.2.1.RELEASE</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb-cross-store</artifactId>
- <version>1.2.1.RELEASE</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-mongodb-log4j</artifactId>
- <version>1.2.1.RELEASE</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- </dependencies>
4.2 添加spring配置文件
spring的配置文件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:context="http://www.springframework.org/schema/context"
- 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-1.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:component-scan base-package="liming.mongodb.example" />
- <mongo:mongo host="127.0.0.1" port="27017" />
- <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
- <mongo:db-factory dbname="student" mongo-ref="mongo" />
- <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
- <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
- </bean>
- <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
- <mongo:mapping-converter base-package="climing.mongodb.example.data.model" />
- <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
- <mongo:repositories base-package="liming.mongodb.example.data.impl" />
- <context:annotation-config />
- </beans>
4.3 增删改查
Userl实现的增删改查:
4.3.1UserEntity
- package liming.mongodb.example.data.model;
- import java.util.Date;
- import org.springframework.data.annotation.Id;
- import org.springframework.data.mongodb.core.mapping.Document;
- @Document(collection = "user")
- public class UserEntity {
- @Id
- private String id;
- private NameEntity name;
- private int age;
- private int works;
- private Date birth;
- private String password;
- private String regionName;
- private String[] special;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public NameEntity getName() {
- return name;
- }
- public void setName(NameEntity name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getWorks() {
- return works;
- }
- public void setWorks(int works) {
- this.works = works;
- }
- public Date getBirth() {
- return birth;
- }
- public void setBirth(Date birth) {
- this.birth = birth;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getRegionName() {
- return regionName;
- }
- public void setRegionName(String regionName) {
- this.regionName = regionName;
- }
- public String[] getSpecial() {
- return special;
- }
- public void setSpecial(String[] special) {
- this.special = special;
- }
- }
4.3.2 NameEntity
- package liming.mongodb.example.data.model;
- public class NameEntity {
- private String username;
- private String nickname;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getNickname() {
- return nickname;
- }
- public void setNickname(String nickname) {
- this.nickname = nickname;
- }
- }
4.3.3 UserDao
- package liming.mongodb.example.data;
- import java.util.List;
- import liming.mongodb.example.data.model.UserEntity;
- import org.springframework.transaction.annotation.Transactional;
- @Transactional
- public interface UserDao {
- public abstract void _test();
- public abstract void createCollection();
- public abstract List<UserEntity> findList(int skip, int limit);
- public abstract List<UserEntity> findListByAge(int age);
- public abstract UserEntity findOne(String id);
- public abstract UserEntity findOneByUsername(String username);
- public abstract void insert(UserEntity entity);
- public abstract void update(UserEntity entity);
- }
4.3.4 UserDaoImpl
- package liming.mongodb.example.data.impl;
- import java.util.List;
- import java.util.Set;
- import liming.mongodb.example.data.UserDao;
- import liming.mongodb.example.data.model.UserEntity;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.domain.Sort.Direction;
- import org.springframework.data.domain.Sort.Order;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.query.Criteria;
- import org.springframework.data.mongodb.core.query.Query;
- import org.springframework.data.mongodb.core.query.Update;
- import org.springframework.stereotype.Repository;
- import com.mongodb.DB;
- @Repository
- public class UserDaoImpl implements UserDao {
- public static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
- @Autowired
- private MongoTemplate mongoTemplate;
- @Override
- public void _test() {
- Set<String> colls = this.mongoTemplate.getCollectionNames();
- for (String coll : colls) {
- logger.info("CollectionName=" + coll);
- }
- DB db = this.mongoTemplate.getDb();
- logger.info("db=" + db.toString());
- }
- @Override
- public void createCollection() {
- if (!this.mongoTemplate.collectionExists(UserEntity.class)) {
- this.mongoTemplate.createCollection(UserEntity.class);
- }
- }
- @Override
- public List<UserEntity> findList(int skip, int limit) {
- Query query = new Query();
- query.with(new Sort(new Order(Direction.ASC, "_id")));
- query.skip(skip).limit(limit);
- return this.mongoTemplate.find(query, UserEntity.class);
- }
- @Override
- public List<UserEntity> findListByAge(int age) {
- Query query = new Query();
- query.addCriteria(new Criteria("age").is(age));
- return this.mongoTemplate.find(query, UserEntity.class);
- }
- @Override
- public UserEntity findOne(String id) {
- Query query = new Query();
- query.addCriteria(new Criteria("_id").is(id));
- return this.mongoTemplate.findOne(query, UserEntity.class);
- }
- @Override
- public UserEntity findOneByUsername(String username) {
- Query query = new Query();
- query.addCriteria(new Criteria("name.username").is(username));
- return this.mongoTemplate.findOne(query, UserEntity.class);
- }
- @Override
- public void insert(UserEntity entity) {
- this.mongoTemplate.insert(entity);
- }
- @Override
- public void update(UserEntity entity) {
- Query query = new Query();
- query.addCriteria(new Criteria("_id").is(entity.getId()));
- Update update = new Update();
- update.set("age", entity.getAge());
- update.set("password", entity.getPassword());
- update.set("regionName", entity.getRegionName());
- update.set("special", entity.getSpecial());
- update.set("works", entity.getWorks());
- update.set("name", entity.getName());
- this.mongoTemplate.updateFirst(query, update, UserEntity.class);
- }
- }
4.3.5 测试代码
- package liming.mongodb.example;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.List;
- import liming.mongodb.example.data.UserDao;
- import liming.mongodb.example.data.impl.UserDaoImpl;
- import liming.mongodb.example.data.model.UserEntity;
- import org.springframework.context.ConfigurableApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class ApplicationSpring {
- public static void main(String[] args) {
- System.out.println("Bootstrapping HelloMongo");
- ConfigurableApplicationContext context = null;
- context = new ClassPathXmlApplicationContext("applicationContext.xml");
- UserDao userDao = context.getBean(UserDaoImpl.class);
- userDao._test();
- UserEntity entity1 = new UserEntity();
- entity1.setId("5");
- entity1.setAge(1);
- entity1.setBirth(new Date());
- entity1.setPassword("asdfasdf");
- entity1.setRegionName("北京");
- entity1.setWorks(1);
- userDao.insert(entity1);
- userDao.update(entity1);
- userDao.createCollection();
- List<UserEntity> list = userDao.findList(0, 10);
- for (UserEntity e : list) {
- System.out.println("all - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
- + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- }
- list = userDao.findListByAge(1);
- for (UserEntity e : list) {
- System.out.println("age=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
- + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- }
- UserEntity e = userDao.findOne("1");
- System.out.println("id=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
- + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- e = userDao.findOneByUsername("limingnihao");
- System.out.println("username=limingnihao - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
- + Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
- System.out.println("DONE!");
- }
- }