如何实现此代码的等价物:
tx.begin();
Widget w = em.find(Widget.class, 1L, LockModeType.PESSIMISTIC_WRITE);
w.decrementBy(4);
em.flush();
tx.commit();
...但是使用Spring和Spring-Data-JPA注释?
我现有代码的基础是:
@Service
@Transactional(readOnly = true)
public class WidgetServiceImpl implements WidgetService
{
  /** The spring-data widget repository which extends CrudRepository<Widget, Long>. */
  @Autowired
  private WidgetRepository repo;
  @Transactional(readOnly = false)
  public void updateWidgetStock(Long id, int count)
  {
    Widget w = this.repo.findOne(id);
    w.decrementBy(4);
    this.repo.save(w);
  }
}
但我不知道如何指定updateWidgetStock方法中的所有内容都应该使用悲观的锁定集来完成.
有一个Spring Data JPA注释org.springframework.data.jpa.repository.Lock允许你设置一个LockModeType,但我不知道将它放在updateWidgetStock方法上是否有效.这听起来更像是一个注释WidgetRepository,因为Javadoc说:
org.springframework.data.jpa.repository
@Target(value = METHOD)
@Retention(value = RUNTIME)
@Documented
public @interface Lock …
如何@Lock为查询指定超时.我正在使用oracle 11g,我希望我可以使用类似的东西'select id from table where id = ?1 for update wait 5'.
我定义了这样的方法,
@Lock(LockModeType.PESSIMISTIC_WRITE)
Stock findById(String id);
它似乎永远锁定.我开始javax.persistence.lock.timeout=0了LocalContainerEntityManagerFactoryBean.jpaProperties,但没有受到影响.
目前我一直在使用以下Spring JPA Repository基础自定义查询,它工作正常,
 @Query("SELECT usr FROM User usr  WHERE usr.configurable = TRUE "
              + "AND (" +
                        "lower(usr.name) like lower(:filterText) OR lower(usr.userType.classType.displayName) like lower(:filterText) OR lower(usr.userType.model) like lower(:filterText)"
              +      ")"
              + "")
  public List<User> findByFilterText(@Param("filterText") String filterText, Sort sort);
当过滤器文本将成为逗号分隔值时,我需要修改此查询.但是按照以下方式,它将是一个动态查询,我该如何执行它.
我需要构建动态查询,
String sql = "SELECT usr FROM User usr WHERE usr.configurable = TRUE";
for(String word : filterText.split(",")) {
                sql += " AND (lower(usr.name) like lower(:" + word + ") OR lower(usr.userType.classType.displayName) like lower(:" + word + ") OR lower(usr.userType.model) like …我正在使用Spring Data JPA开展项目.我在数据库中有一个表作为my_query.
我想创建一个方法,该方法将字符串作为参数,然后在数据库中将其作为查询执行.
方法:
executeMyQuery(queryString)
例如,当我通过
queryString= "SELECT * FROM my_query"
那么它应该在DB级别运行该查询.
存储库类如下.
public interface MyQueryRepository extends JpaRepository<MyQuery, Long>{
    public MyQuery findById(long id);
    @Modifying(clearAutomatically = true)
    @Transactional
    @Query(value = "?1", nativeQuery = true)
    public void executeMyQuery(String query);
}
但是,它没有像我预期的那样工作.它给出以下错误.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''select * from my_query;'' at line 1
还有其他办法,我可以实现这个目标.提前致谢
我有两个Entitymanagerbean配置.每个指向具有不同模式的单独数据库(一个是Oracle,另一个是内存中的H2)
我该怎么做才能解决Entitymanager应该用于每个存储库的模糊性?现在我收到这个错误:
 No unique bean of type [javax.persistence.EntityManagerFactory] is defined:
 expected single bean but found 2
我想我可以通过使用类似的东西来提供快速修复
<jpa:repositories base-package="com.foo.repos.ora"
 entity-manager-factory-ref="entityManagerFactoryA">
<jpa:repositories base-package="com.foo.repos.m2"
 entity-manager-factory-ref="entityManagerFactoryB">
但希望有更好的解决方案.
编辑:
我给你一个当前场景的想法:
Spring-Config:有两个EM
<jpa:repositories base-package="com.foo.repos.ora" entity-manager-factory-ref="entityManagerFactory"/>
<jpa:repositories base-package="com.foo.repos.m2" entity-manager-factory-ref="entityManagerFactory2"/>
<context:component-scan base-package="com.foo" />  ....
这里的所有内容都在"package com.foo.repos.ora"中.遵循如何创建自定义存储库的模式我得到两个接口'ARepository','ARepositoryCustom'及其实现'ARepositoryImpl'就像这样
@Repository
public interface ARepository extends ARepositoryCustom, JpaRepository<myEntity, BigDecimal>, QueryDslPredicateExecutor {
}
public interface ARepositoryCustom {
    FooBar lookupFooBar()
}
public class ARepositoryImpl extends QueryDslRepositorySupport implements ARepositoryCustom {
    ARepositoryImpl(Class<?> domainClass) {
        super(domainClass.class)
    }
    ARepositoryImpl() {
        this(myEntity.class)
    }
    @Override
    FooBar …我使用Spring Data JPA 1.7.1和Hibernate 4.3.7作为我的JPA提供程序.我有以下Spring Data JPA存储库:
@Repository
public interface CompanyRepository extends JpaRepository<Company, Integer> {
    @EntityGraph(value = "graph.company.search.results", type = EntityGraph.EntityGraphType.FETCH)
    @Query("SELECT c FROM Company c WHERE c.id IN :companyIds")
    List<Company> findByCompanyIdsForSearchResults(@Param("companyIds") Set<Integer> companyIds);
}
以下代码调用上面的存储库方法:
Set<Integer> companyIds = new HashSet<>();
companyIds.add(100000);
// companyIds.add(100001); // This line breaks the code
List<Company> companies = this.companyRepository.findByCompanyIdsForSearchResults(companyIds);
我正在经历上述的奇怪行为.首先,如果我只在集合中放入一个ID,那么我的列表中会返回两个 Company实例,即使ID显然是唯一的.其次,如果我向集合中添加了多个ID,则代码将失败并显示以下内容NullPointerException:
java.lang.NullPointerException
    org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
    org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:616)
    org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1901)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
    org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1839)
    org.hibernate.loader.Loader.doQuery(Loader.java:910)
    org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
    org.hibernate.loader.Loader.doList(Loader.java:2554)
    org.hibernate.loader.Loader.doList(Loader.java:2540)
    org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
    org.hibernate.loader.Loader.list(Loader.java:2365)
    org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
    org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236)
    org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
    org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
    org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:449)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native …我想扩展一个JpaRepository自定义实现,所以我添加了一个MyRepositoryCustom接口和一个MyRepositoryImpl扩展此接口的类.
有没有办法从JpaRepository我的自定义类中调用方法?
注意:这也是作为对/sf/answers/831684241/的评论而提出的,但我认为值得一个单独的问题是很常见的.
我已在 Spring Data JpaRespository 上添加了一个具有单个自定义方法的自定义接口,如该问题的答案中所述;
但是现在我收到以下错误;
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property customMethod found for type Account!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241)
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
这似乎是因为 Spring Data 试图生成“customMethod”的查询,认为它是“Account”的属性。
如何停止给定方法的自动查询生成?!
更新我的代码具体如下;
public interface CacheInvalidatingRepo<T> {
    public void invalidateCache(T obj);
}
@Component
public class CacheInvalidatingRepoImpl<T> implements CacheInvalidatingRepo<T> {
    @Override
    public void invalidateCache(T obj) {
        // kill the entity manager cache
    }
}
public interface VerificationRepo extends JpaRepository<Verification, BigInteger>, JpaSpecificationExecutor<Verification>, CacheInvalidatingRepo<Verification> {
}
结果如下; …
我想创建自定义存储库:
public interface FriendRepositoryCustom {
    Page<Friend> findFriends(FriendCriteria friendCriteria, Pageable pageable);
}
及其实现:
@Repository
@Transactional(readOnly = true)
public class FriendRepositoryCustomImpl implements FriendRepositoryCustom {
    @PersistenceContext
    EntityManager entityManager;
    @Override
    public Page<Friend> findFriends(FriendCriteria friendCriteria, Pageable pageable) {
    ...
    }
并将其添加到主存储库:
@Repository
public interface FriendRepository extends JpaRepository<Friend, Long>, JpaSpecificationExecutor<Friend>, FriendRepositoryCustom {
}
当我启动应用程序时,出现此错误:
由以下原因引起:org.springframework.data.mapping.PropertyReferenceException:未找到类型为Friend的属性findFriends!在org.springframework.data.mapping.PropertyPath。(PropertyPath.java:77)在org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)在org.springframework.data.mapping.PropertyPath.create( org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)上的PropertyPath.java:309)org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243)上的org.springframework.data org.springframework.data.repository.query.parser.PartTree $ OrPart。(PartTree.java:247)的org.springframework.data.repository.query的.repository.query.parser.Part。(Part.java:76) org.springframework.data.repository的.parser.PartTree $ Predicate.buildTree(PartTree.java:398)。
我正在使用JpaSpecificationExecutor,JPA 2.0,Hibernate和MSSQL,并希望使用CriteriaBuilder构建以下查询:
SELECT CURR_DATE, MAX(POSITION) FROM TOP_COMPONENT_HISTORY GROUP BY CURR_DATE
我的问题:可能吗?如果,怎么办?
多谢您为此下定决心!
这是我的代码。
表格(TOP_COMPONENT_HISTORY)
1   ARC_ID  varchar NO          
2   CURR_DATE   varchar NO          
3   REG_DATE    datetime2   YES         7
4   APPLY_DATE  datetime2   YES         7
5   POSITION    int YES 10  0   
6   REG_USER_ID varchar NO          
7   MOD_USER_ID varchar NO  
服务
public Page<TopComponentHistory> findByCurrDate(ArticleSearchForm searchForm){
        return topComponentHistoryRepository.findAll(TopComponentHistory.findAllGroupBy(),constructPageSpecification(searchForm.getPageNum());
    }
域
public class TopComponentHistory implements Serializable {
    public static Specification<TopComponentHistory> findAllGroupBy() {     
       How can i make query...
       return ..
    }
}
资料库
public interface TopComponentHistoryRepository extends …我有一个具有复合键的实体,我试图通过使用 spring data jpa 存储库到 mysql 数据库来持久化它,如下所示:
@Embeddable
public class MobileVerificationKey implements Serializable{
private static final long serialVersionUID = 1L;
@Column(name="CUSTOMERID")
private Long customerId;
@Column(name="CUSTOMERTYPE")
private Integer customerType;
@Column(name="MOBILE")
private Long mobile;
@Embeddable
public class MobileVerificationKey implements Serializable{
    private static final long serialVersionUID = 1L;
    @Column(name="CUSTOMERID")
    private Long customerId;
    @Column(name="CUSTOMERTYPE")
    private Integer customerType;
    @Column(name="MOBILE")
    private Long mobile;
//getter and setters
}
和实体作为
@Entity
@Table(name="mobileverificationdetails")
public class MobileVerificationDetails {
    @EmbeddedId
    private MobileVerificationKey key;
    @Column(name="MOBILETYPE")
    private String mobileType;
    @Column(name="MOBILEPIN")
    private Integer mobilePin; …我最近开始使用Spring启动,并遇到了一些问题.之前,当我刚刚使用Spring数据和hibernate和JPA时,我可以创建一个hibernate.cfg.xml文件,该文件可以提供一系列可以传递给配置对象的配置,然后最终创建一个SessionFactory对象来创建一个可用于将查询传递给hibernate的Session对象:
package util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() { 
        try {
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); return configuration.buildSessionFactory( new
        StandardServiceRegistryBuilder().applySettings( configuration.getProperties() ).build() ); 
        }
        catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex);
        } 
    }
    public static SessionFactory getSessionFactory() { return sessionFactory; …我需要编写一个select查询从Spring Data Repository层中的多个表中获取数据.我知道我们可以使用@Query编写自定义查询,但只返回单个表中的值?
SELECT s.service_id, s.name, us.rating_id 
FROM services s, 
     ratings r, 
     user_services us
where 
    us.service_id = s.service_id and
    us.rating_id = r.rating_id and
    us.user_id= ?;
spring-data-jpa ×11
java ×8
spring ×8
spring-data ×8
jpa ×6
hibernate ×5
hql ×2
spring-boot ×2
jhipster ×1
jpa-2.0 ×1
mysql ×1
oracle ×1
sql ×1