标签: spring-data

Spring Data加入规范

我正在尝试转换这个原始的SQL查询:

select product.* from following_relationship
join product on following_relationship.following=product.owner_id
where following_relationship.owner=input 
Run Code Online (Sandbox Code Playgroud)

进入Spring Data规范,我认为到目前为止我的问题是加入这些表.

这是我目前在规范中的转换:

protected Specification<Product> test(final User user){
   return new Specification<Product>() {
       @Override
       public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
           Join<FollowingRelationship,Product> pfJoin = query.from(FollowingRelationship.class).join("following");
           pfJoin.on(cb.equal(pfJoin.get("following"),"owner"));
           return  query.where(cb.equal(pfJoin.get("following"),user)).getGroupRestriction();

       }
   };
}
Run Code Online (Sandbox Code Playgroud)

我得到了这个例外:

Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessA
piUsageException: org.hibernate.hql.internal.ast.InvalidWithClauseException: with clause can only reference columns in the driving table 
Run Code Online (Sandbox Code Playgroud)

我想补充一点,我是Spring框架的新手,例如这是我春天的第一个应用程序,所以我为新手问题道歉;)

编辑:添加的实体Product,FollowingRelationShip

Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "json_id_prop")
public class FollowingRelationship extends BaseEntity {

    @ManyToOne(fetch = …
Run Code Online (Sandbox Code Playgroud)

java mysql spring spring-data

15
推荐指数
1
解决办法
2万
查看次数

域驱动设计存储库与Spring Data存储库之间是否存在不匹配?

DDD指定每个聚合的存储库,但是当采用Spring Data JPA时,我们只有在声明每个实体的接口时才能利用这些优势.如何解决阻抗不匹配问题?

我希望尝试封装在聚合存储库中的存储库接口,这是一个好的解决方案还是更好的可用解决方案?

到给定的一个例子:Customer是聚合根和实体等Demographics,Identification,AssetSummary等等,其中每个实体可以从具有自己的资源库接口受益.没有违反DDD的最佳方法是什么?

domain-driven-design ddd-repositories spring-data spring-data-jpa

15
推荐指数
1
解决办法
2343
查看次数

SpringBoot:无法从其他Jar库自动装配类

我正在开发一个SpringBoot应用程序(例如MyApp),它依赖于两个具有不同实现的数据项目:

数据了jdbc.jar

  • 使用spring-boot-starter-jdbcmy来构建公开我的应用程序将使用的JDBCDataService类

示例代码:

@Service 
public class JDBCDataServiceImpl implements JDBCDataService {

@Autowired
private JDBCDataRepository jdbcDataRepository;    
... 
}
Run Code Online (Sandbox Code Playgroud)
  • 与包 my.data.jdbc
  • 没有SpringBoot主类.仅为单元测试类创建Spring配置
  • 存储库类正在使用 JDBCTemplate

样本库:

@Repository
public class JDBCDataRepositoryImpl implements JDBCDataRepository {

@Autowired
protected JdbcTemplate jdbcTemplate;
...
}
Run Code Online (Sandbox Code Playgroud)

数据jpa.jar

  • 使用the构建spring-boot-starter-data-jpa也暴露了我的应用程序也将使用的JPADataService类

示例代码:

@Service 
public class JPADataServiceImpl implements JPADataService {

@Autowired
private JPADataRepository jpaDataRepository;    
... 
}
Run Code Online (Sandbox Code Playgroud)
  • 与包 my.data.jpa
  • 没有SpringBoot主类.仅为单元测试类创建Spring配置
  • 存储库类扩展了CrudRepository接口

样本库:

@Repository
public interface JPADataRepository extends CrudRepository<MyObject, Integer{
...
}
Run Code Online (Sandbox Code Playgroud)

在我的SpringBoot项目中,我有以下SpringBoot主应用程序:

@SpringBootApplication
public class MyApp extends SpringBootServletInitializer { …
Run Code Online (Sandbox Code Playgroud)

java jdbc spring-data spring-data-jpa spring-boot

15
推荐指数
2
解决办法
2万
查看次数

@EnableAutoConfiguration(exclude =...) 在 Spring Boot 2.6.0 中测试失败

我尝试将我的 data-mongo 示例项目升级到 Spring Boot 2.6.0。有一个设计用于针对 Testcontainers 运行的测试,我还包含了用于其他测试的嵌入式 mongo dep,因此我必须排除嵌入式 mongo 的自动配置,以确保此测试在 Docker/testcontainers 上运行。

以下配置适用于 Spring Boot 2.5.6


@DataMongoTest
@ContextConfiguration(initializers = {MongodbContainerInitializer.class})
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@Slf4j
@ActiveProfiles("test")
public class PostRepositoryTest {}
Run Code Online (Sandbox Code Playgroud)

但是升级到 Spring Boot 2.6.0 并运行应用程序后,我得到了这样的异常。

[           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: o
rg.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'embeddedMongoServer' defined in class path resource [org/springframework/boot/autoconfig
ure/mongo/embedded/EmbeddedMongoAutoConfiguration.class]: Unsatisfied dependency expressed through method 'embeddedMongoServer' parameter 0; nested exception is org.springframework.bea
ns.factory.BeanCreationException: Error creating …
Run Code Online (Sandbox Code Playgroud)

spring spring-data spring-boot spring-data-mongodb-reactive

15
推荐指数
3
解决办法
2万
查看次数

Hibernate具有相同where子句的二级查询缓存问题

我的应用程序使用JPA(1.2),Spring(3.1.2),Spring Data(1.1.0)和Hibernate(4.1.7).数据库:Oracle10g

我们启用了二级缓存.它与实体一起工作正常但它在命名查询缓存上创建了问题.

问题是:如果命名查询具有相同的where子句但是具有不同的select语句,那么无论第一个查询执行它还是为第二个查询提供相同的结果.

就像我的第一个查询(countRelease)一样

select count(r) from Release r where r.type in 
(select c.contentTypeId from ContentType c where c.parentContentTypeId is NULL)
order by r.validityStart
Run Code Online (Sandbox Code Playgroud)

和第二个查询(findRelease)是

select r from Release r where r.type in 
(select c.contentTypeId from ContentType c where c.parentContentTypeId is NULL)   
order by r.validityStart
Run Code Online (Sandbox Code Playgroud)

如果先运行第一个查询,那么计数将会到来,之后如果我运行第二个查询,那么还会计数它应该给我发布实体的列表.

如果我删除查询缓存它工作正常,如果我在第二个查询where子句中进行一些更改,那么它也工作正常,但我不需要这样做.

我们如何解决这个问题?

我的Java代码

@Query(name="findRelease")
@QueryHints({@QueryHint(name = "org.hibernate.cacheRegion", value ="cvodrelease"),@QueryHint(name = "org.hibernate.cacheable", value ="true") })
public List<Release> findRelease();

@Query(name="countRelease")
@QueryHints({@QueryHint(name = "org.hibernate.cacheRegion", value ="cvodrelease"),@QueryHint(name = "org.hibernate.cacheable", value ="true") })
public Long  countOfRelease(Date today);
Run Code Online (Sandbox Code Playgroud)

缓存配置 …

java hibernate jpa spring-data spring-data-jpa

14
推荐指数
1
解决办法
7472
查看次数

hibernate + spring数据中的本机插入查询

我尝试将以下代码添加到spring数据jpa存储库:

  @Query("insert into commit_activity_link (commit_id, activity_id) VALUES (?1, ?2)")
  void insertLinkToActivity(long commitId, long activityId);
Run Code Online (Sandbox Code Playgroud)

但app不能以例外开头:

引起:org.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌:VALUES靠近第1行第59列[insert into commit_activity_link(commit_id,activity_id)VALUES(?1,?2)]

哪里我错了?

sql hibernate spring-data

14
推荐指数
1
解决办法
2万
查看次数

如何在自定义实现中访问Spring Data配置的实体管理器(工厂)

我正在为Spring Data JPA存储库编写自定义实现.所以我有:

  • MyEntityRepositoryCustom =>与自定义方法的接口
  • MyEntityRepositoryUmpl =>执行上面的接口
  • MyEntityRepository=>标准接口,扩展JpaRepositoryMyEntityRepositoryCustom

我的问题是:在MyEntityRepositoryUmpl我需要访问注入Spring Data的实体管理器的实现中.怎么弄?我可以使用@PersistenceContext它来自动装配,但问题是此存储库必须在设置多个持久性单元的应用程序中工作.所以,要告诉Spring我需要哪一个,我将不得不使用@PersistenceContext(unitName="myUnit").但是,由于我的存储库是在可重用的服务层中定义的,因此我无法知道更高级别的应用程序层将配置为注入我的存储库的持久性单元的名称.

换句话说,我需要做的是访问Spring Data本身正在使用的实体管理器,但是在查看Spring Data JPA文档(不那么快)后,我找不到任何相关内容.

老实说,这些Impl类完全没有意识到Spring Data,尽管在Spring Data手册中被描述为一个优势,但实际上每当你需要访问通常由Spring Data本身在自定义实现中提供的东西时(实际上,我会说...).

spring-data spring-data-jpa

14
推荐指数
2
解决办法
3万
查看次数

在Spring Boot中获取EntityManager的句柄

有没有办法获得给定实体对象的EntityManager句柄?我正在使用带有JPA启动器的spring boot 1.2.3,并且我进一步明确地配置了多个数据源@configuration

我检查了[已解决] SPRING BOOT对entityManager的访问权限,似乎没有回答这个问题.

谢谢.

编辑:我添加了如何定义数据源的说明:

@Component
@Configuration
public class DataSources {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="first.datasource")
    public DataSource getPrimaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="second.datasource")
    public DataSource getSecondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="third.final.datasource")
    public DataSource getThirdFinalDataSource() {
        return DataSourceBuilder.create().build();
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的application.yml中,我有以下部分

first.datasource:
  name: 'first_datasource',
  #other attributes...
second.datasource:
  name: 'second_datasource',
  #other attributes...
third.final.datasource:
  name: 'first_datasource',
  #other attributes...
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试了@ Stephane的两个建议,但我得到了 NoSuchBeanDefinitionException

假设我的实体被调用Customer然后我试过了

@Service
public class FooService {

    private final EntityManager entityManager;

    @Autowired
    public FooService(@Qualifier("customerEntityManager") …
Run Code Online (Sandbox Code Playgroud)

java jpa spring-data spring-data-jpa spring-boot

14
推荐指数
1
解决办法
3万
查看次数

排除hibernate创建的特定表?

我有一个@Entity映射到视图,这是它的外观

import org.hibernate.annotations.Immutable;
import javax.persistence.*;

@Table(name = "user_earning")
@Entity
@Immutable
public class UserFlightEarning {
    @Id public Long userId;
    public Long flightId;
    @Column(name = "flight_seq") public Long flightSequence;
}
Run Code Online (Sandbox Code Playgroud)

这很好用,我可以使用dao从视图中检索记录.但是我在日志中注意到Hibernate实际上是在尝试创建表但由于它已经存在而失败.

2015-11-12 21:56:34.841 ERROR 4204 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport:HHH000389:不成功:create table user_profile(user_id bigint not null,avg_airtime integer,avg_fuel_points integer ,avg_miles integer,email varchar(255),first_name varchar(255),flights_count integer,furthest_flight integer,last_name varchar(255),longest_flight integer,most_visited_city varchar(255),tier_end integer,tier_start integer,primary key(user_id))2015 -11-12 21:56:34.841 ERROR 4204 --- [ost-startStop-1] org.hibernate.tool.hbm2ddl.SchemaExport:表'user_profile'已经存在

我可以配置hibernate,以便跳过这些实体的创建吗?我认为@Immutable注释告诉Hibernate跳过创建,但似乎这个注释只是为了防止表上的crud操作.

spring hibernate jpa spring-data

14
推荐指数
1
解决办法
4447
查看次数

如何在不破坏自动配置的情况下自定义Spring-Boot中的MappingMongoConverter(setMapKeyDotReplacement)?

如何MappingMongoConverter在不更改由spring-data自动配置的任何mongo-stuff的情况下自定义Spring-Boot-Application(1.3.2.RELEASE)中的内容?

我目前的解决方案是:

@Configuration
public class MongoConfig {

  @Autowired
  private MongoDbFactory mongoFactory;

  @Autowired
  private MongoMappingContext mongoMappingContext;

  @Bean
  public MappingMongoConverter mongoConverter() throws Exception {
    DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoFactory);
    MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
    //this is my customization
    mongoConverter.setMapKeyDotReplacement("_");
    mongoConverter.afterPropertiesSet();
    return mongoConverter;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是正确的方式还是我打破了一些东西?
或者是否有更简单的方法来设置mapKeyDotReplacement?

spring-data spring-data-mongodb spring-boot

14
推荐指数
3
解决办法
6295
查看次数