我正在使用MongoDB使用Spring数据和MongoDB.
我想知道是否可以使用查询注释通过过滤器进行删除.我一直在这里和谷歌,我找不到任何文件.
我有以下类要使用Spring Data存储在MongoDB中
@Document()
public class Tuple2<T extends Enum<T>> {
@Id
private String id;
@Indexed
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private final Instant timeCreated;
...
}
Run Code Online (Sandbox Code Playgroud)
DateTimeFormat注释javadoc状态:
声明字段应格式化为日期时间.支持按样式模式,ISO日期时间模式或自定义格式模式字符串格式化.可以应用于java.util.Date,java.util.Calendar,java.long.Long,Joda-Time值类型; 从Spring 4和JDK 8开始,到JSR-310也是java.time类型.
我使用的是Spring 4.1.1和JDK 8,所以我希望它适用于Instant.但是,这是实际存储的内容:
"timeCreated" : {
"seconds" : NumberLong(1416757496),
"nanos" : 503000000
}
Run Code Online (Sandbox Code Playgroud)
如果我从即时到日期编写和注册自定义转换器,就像在这个答案中解释的一样,那么它是有效的,但是我想避免这种情况,因为我确信必须有更好的方法.
在进一步挖掘Spring源代码之后,我发现了以下Jsr310DateTimeFormatAnnotationFormatterFactory看起来很有希望的类:
使用JDK 8中的JSR-310 java.time包格式化使用DateTimeFormat注释注释的字段.
它的'源代码没有引用Instant,但确实引用了OffsetTime和LocalTime.即便如此,当我在我的示例中将Instant更改为OffsetDateTime时,它仍然存储为复合对象而不是ISODate.
缺什么?
我工作spring data,我创建一个配置类@Bean,@Entity以及Main.java但是跑项目时,我得到异常:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class entity.Todo
我的Main.java
public class Main {
@Autowired
private static TodoRepository todoRepository;
public static void main(String[] args) {
Todo todo = new Todo();
todo.setId(1l);
todo.setTitle("title");
System.out.println(todoRepository); //null
todoRepository.save(todo); //Exception in thread "main" java.lang.NullPointerException
}
}
Run Code Online (Sandbox Code Playgroud)
PersistenceContext.java
@Configuration
@EnableJpaRepositories(basePackages = {"repository"},
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = …Run Code Online (Sandbox Code Playgroud) 如何将以下 MongoDB 查询转换为 Java Spring 应用程序要使用的查询?我找不到使用pipeline提供的查找方法的方法。
这是我试图转换的查询。我还想指出,我没有使用,$unwind因为我希望将deliveryZipCodeTimings保留为返回对象中的分组集合。
db.getCollection('fulfillmentChannel').aggregate([
{
$match: {
"dayOfWeek": "SOME_VARIABLE_STRING_1"
}
},
{
$lookup: {
from: "deliveryZipCodeTiming",
let: { location_id: "$fulfillmentLocationId" },
pipeline: [{
$match: {
$expr: {
$and: [
{$eq: ["$fulfillmentLocationId", "$$location_id"]},
{$eq: ["$zipCode", "SOME_VARIABLE_STRING_2"]}
]
}
}
},
{
$project: { _id: 0, zipCode: 1, cutoffTime: 1 }
}],
as: "deliveryZipCodeTimings"
}
},
{
$match: {
"deliveryZipCodeTimings": {$ne: []}
}
}
])
Run Code Online (Sandbox Code Playgroud) spring mongodb spring-data aggregation-framework spring-data-mongodb
我目前正在开发一个在使用JPA和QueryDSL的apache Karaf下运行的OSGi应用程序.
我想知道我是否可以使用SpringDS与QueryDSL而不是当前的方法.
这样做的原因是我发现Spring存储库非常有用,并且拥有NoSQL数据库访问模板将来可能会有用.
我试图在没有OSGi的Web上下文的情况下启动普通的spring应用程序,但是当它尝试加载applicationContext.xml或ApplicationContext.class时,我得到了一个ClassNoutFoundException.
我不想使用Spring DM,因为它已经停产.
基本上,想要尝试这种集成的唯一原因是Spring Repositories,但如果您认为这不是必要的,请告诉我.有关如何实现这一点的任何信息,或者是否可以继续这样做将非常受欢迎.
谢谢
更新
我已经设法通过启动应用程序上下文来使弹簧工作org.eclipse.gemini.blueprint.context.support.OsgiBundleXmlApplicationContext.applicationContext作为服务在OSGi中导出,我可以通过调用它来获取所需的所有bean.
我现在遇到的问题是,当我声明<jpa:repositories base-package="x.y.z" />我得到以下异常时:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [bundle://251.13:0/META-INF/spring/applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: No persistence exception translators found in bean factory. Cannot perform exception translation.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)[185:org.springframework.beans:3.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109)[187:org.springframework.context:3.1.4.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.registerBeanPostProcessors(AbstractDelegatedExecutionApplicationContext.java:502)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.registerBeanPostProcessors(AbstractDelegatedExecutionApplicationContext.java:451)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext$4.run(AbstractDelegatedExecutionApplicationContext.java:306)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.util.internal.PrivilegedUtils.executeWithCustomTCCL(PrivilegedUtils.java:85)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.context.support.AbstractDelegatedExecutionApplicationContext.completeRefresh(AbstractDelegatedExecutionApplicationContext.java:290)[193:org.eclipse.gemini.blueprint.core:1.0.0.RELEASE]
at org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor$CompleteRefreshTask.run(DependencyWaiterApplicationContextExecutor.java:137)[194:org.eclipse.gemini.blueprint.extender:1.0.0.RELEASE]
at java.lang.Thread.run(Thread.java:662)[:1.6.0_37]
Caused by: …Run Code Online (Sandbox Code Playgroud) 我想使用Spring数据JPA获取随机记录.我正在使用@Query.但这需要很长时间.
@Query("select que from Question que order by RAND()")
public List<Question> findRandamQuestions();
Run Code Online (Sandbox Code Playgroud)
这样做的有效方法是哪种?请帮忙!
我正在寻找一个使用Spring Data JPA动态构建查询的解决方案.我有一个GameController,它有一个RESTful服务端点/游戏,有4个可选参数:流派,平台,年份,标题.API可以不传递,全部4,以及它们之间的每个组合.如果未传递任何参数,则默认为null.我需要一个存储库中的方法来构建适当的查询,理想情况下仍然允许Spring Data JPA Paging,尽管我不确定这是否可行.
我找到了这篇文章,但除非我误解,否则这似乎不是我需要的.http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
我知道JPA有一个Query Criteria API,但实际上并不知道如何实现它.
我意识到我可以为每个可能的场景创建一个方法,但这似乎是非常糟糕的做法和许多不必要的代码.
GameRepository:
package net.jkratz.igdb.repository;
import net.jkratz.igdb.model.Game;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface GameRepository extends JpaRepository<Game, Long> {
@Query("select g from Game g, GamePlatformMap gpm, Platform p where g = gpm.game and gpm.platform = p and p.id = :platform")
Page<Game> getGamesByPlatform(@Param("platform") Long platformId, Pageable pageable);
@Query("select g from Game g where g.title like :title")
Page<Game> getGamesByTitle(@Param("title") String title, Pageable pageable);
@Query("select g from Game …Run Code Online (Sandbox Code Playgroud) 当我们使用spring boot和spring数据时,如何访问存储库中的实体管理器?
否则,我需要将我的大查询放在注释中,我宁愿有一些清楚的东西......然后是长文本.
我使用spring-data-jpa和mysql数据库.我的表格字符集是utf-8.我?useUnicode=yes&characterEncoding=utf8还在application.properties文件中添加了mysql url.将"ąčęėį"这样的字符传递给控制器以将其保存在mysql中时出现问题.在mysql我得到了??? 分数.但是当我使用mysql控制台的例子时,update projects_data set data="?????" where id = 1;每个都运行良好.
application.properties:
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:3306/gehive?useUnicode=yes&characterEncoding=utf8
spring.datasource.username = gehive
spring.datasource.password = pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming …Run Code Online (Sandbox Code Playgroud) 我目前正在使用Spring boot 1.4.2,其中我已经使用了Spring-boot-starter-web和Spring-boot-starter-jpa.
我的主要问题是,当我保存一个新实体时,它工作正常(一切都很酷).
但是,如果我保存具有相同id的新产品实体(例如重复条目),则不会抛出异常.我期待ConstrintViolationException或类似的东西.
鉴于以下设置:
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
Run Code Online (Sandbox Code Playgroud)
ProductRepository.java
@Repository
public interface ProductRepository extends JpaRepository<Product, String> {}
Run Code Online (Sandbox Code Playgroud)
JpaConfig.java
@Configuration
@EnableJpaRepositories(basePackages = "com.verric.jpa.repository" )
@EntityScan(basePackageClasses ="com.verric.jpa")
@EnableTransactionManagement
public class JpaConfig {
@Bean
JpaTransactionManager transactionManager() {
return new JpaTransactionManager();
}
}
Run Code Online (Sandbox Code Playgroud)
注意JpaConfig.java和Application.java在同一个包中.
ProductController.java
@RestController
@RequestMapping(path = "/product")
public class ProductController {
@Autowired
ProductRepository productRepository;
@PostMapping("createProduct")
public void handle(@RequestBody @Valid CreateProductRequest request) {
Product product = new Product(request.getId(), request.getName(), request.getPrice(), …Run Code Online (Sandbox Code Playgroud) spring-data ×10
spring ×7
jpa ×4
hibernate ×3
java ×3
mongodb ×2
java-time ×1
mysql ×1
osgi ×1
spring-boot ×1