1.添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>2.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
2.配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.data.mongodb.database=gis spring.data.mongodb.uri=mongodb://localhost:27017
3.mysql操作
实体类
package com.example.demo.model; import lombok.*; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "users") @Data @Builder @ToString(callSuper = true) @NoArgsConstructor @AllArgsConstructor public class Users { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; @Column(updatable = false) @CreationTimestamp private Date createTime; }
数据操作接口
package com.example.demo.repository; import com.example.demo.model.Users; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UsersRepository extends JpaRepository<Users,Integer> { }
控制器方法
@RequestMapping("/users/add") public Users usersAdd(@RequestParam String name) { Users user = Users.builder().name(name).build(); log.info("User {}", user); usersRepository.save(user); return user; }
4.mongo操作
实体类
package com.example.demo.model; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import lombok.*; import org.springframework.data.mongodb.core.mapping.Document; @Document @Data @Builder @ToString(callSuper = true) @NoArgsConstructor @AllArgsConstructor public class Jn { private String type;private JSONObject basic; }
控制器方法
@Resource private MongoTemplate mongoTemplate; @RequestMapping("/mongo") public Result jn() { Query query = new Query(Criteria.where("type").is("abc").andOperator( Criteria.where("basic.x").lte(100).gte(1), Criteria.where("basic.y").lte(50).gte(1) )); List<Jn> list = mongoTemplate.find(query, Jn.class); if(list.size()>0){ return Result.success(200,list); }else{ return Result.failMessage(400,"error"); } }
原文:https://www.cnblogs.com/baby123/p/12627970.html