我正在尝试使用 Spring Data JPA 中的通用存储库执行一些基本的数据库操作。但是,我不断遇到 IllegalArgumentException“不是托管类型:”+我的参数扩展的任何类/接口。
通用存储库.java
@Transactional
public interface GenericRepository<T> extends PagingAndSortingRepository<T, Integer> {
@Query("SELECT g "
+ "FROM " + "#{#entityName}" + " g "
+ "WHERE g.#{#entityName}Id = ?1"
)
public T findById(int Id);
Run Code Online (Sandbox Code Playgroud)
例如,上面的内容抱怨类 Object,而使用 GenericRepository(我试图使用的标记接口)则会抱怨接口 DatabaseDerived 不是托管类型。
我只是在我的大部分设置中使用 @SpringBootApplication ,而我能够找到的这个问题的答案要么在我的情况下肯定不起作用,要么我似乎不知道如何将它们应用到我的应用程序中。设置或者我只是不明白它们。如果有人能给我指出一个有用的教程(在 Google 上找不到)或引导我完成如何在我的设置中使用它,我将不胜感激。
应用程序.java
@SpringBootApplication
@ComponentScan("radius.hibernate")
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>annonymized</groupId>
<artifactId>radius.hibernate</artifactId>
<version>0.1.0</version> …Run Code Online (Sandbox Code Playgroud) 我有一个存储库接口,它扩展了 CrudRepository 以自动为我提供所有基本的 crud 存储库功能。
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
}
Run Code Online (Sandbox Code Playgroud)
我还能添加自定义存储库功能并实现此接口吗?
任何人都可以让我知道,如何使用 spring 数据 JPA 检索特定列的最大值。
我一直在尝试使用 spring 数据 JPA 参考文档中给出的 findTopByOrderByIdDesc 方法,但我得到“'limit'异常附近的语法不正确。
来自 spring 数据 JPA 的方法签名是
用户 findTopByOrderByAgeDesc();
并且我正在尝试使用相同的方法签名,这里该方法不希望传递任何参数,但根据可以的异常,我传递了限制。
甚至我尝试将方法名称更改为 User findTop1ByOrderByIdDesc();
但这确实有效。我不想使用 @Query("some query")
public User getmaxSequence() {
User user=new User();
try {
user= userRepository.findTopByOrderByIdDesc();
}catch(Exception e) {
e.printStackTrace();
}
return user;
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我低于异常堆栈跟踪。
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'limit'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1608)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:578)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:508)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:243)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:218)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:434)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60)
... 150 more
Run Code Online (Sandbox Code Playgroud) 在我的Spring boot项目,我需要查询的表entity名为XrayVulnerabilityEntity具有的能力paging,sorting和specification。
Paging和sorting实施似乎没问题。但是当我添加时Specification,它throws an error是这样的:
引起:org.springframework.beans.factory.BeanCreationException:创建名为“xrayVulnerabilityRepository”的bean时出错:调用init方法失败;嵌套异常是 java.lang.IllegalArgumentException:要么在除 Pageable 和 Sort 类型之外的所有参数上使用 @Param,要么根本不使用!
我使用的存储库:
@Repository
public interface XrayVulnerabilityRepository extends PagingAndSortingRepository<XrayVulnerabilityEntity,XrayVulnerabilityPK> , JpaSpecificationExecutor<XrayVulnerabilityEntity>{
@Query("SELECT x FROM XrayVulnerabilityEntity x,DomainArtifactEntity d WHERE d.domainOrgName=:domainOrgNameParam AND x.domainArtifactId=d")
public Page<XrayVulnerabilityEntity> findAll(@Param(value = "domainOrgNameParam") String domainOrgName,Specification<XrayVulnerabilityEntity> spec, Pageable pageable);
@Query("SELECT COUNT(x) FROM XrayVulnerabilityEntity x,DomainArtifactEntity d WHERE d.domainOrgName=:domainOrgNameParam AND x.domainArtifactId=d")
public Long getCount(@Param(value = "domainOrgNameParam") String domainOrgName,Specification<XrayVulnerabilityEntity> spec);
}
Run Code Online (Sandbox Code Playgroud)
我在实施时做错了 …
我想配置 Spring Boot 以使用 2 个 JNDI 数据源。我试过这个配置:
应用程序属性
spring.production-datasource.jndi-name=java:/global/production_gateway
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.warehouse-datasource.jndi-name=java:/global/production_warehouse
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
Run Code Online (Sandbox Code Playgroud)
主数据库
@Configuration
@EnableJpaRepositories(
basePackages = "org.datalis.plugin.production.entity",
entityManagerFactoryRef = "productionEntityManager",
transactionManagerRef = "productionTransactionManager"
)
@EnableTransactionManagement
public class ContextProductionDatasource {
@Autowired
private Environment env;
@Primary
@Bean
@ConfigurationProperties(prefix="spring.production-datasource")
public DataSource productionDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean
public EntityManager productionEntityManager(EntityManagerFactory emf) {
return emf.createEntityManager();
}
@Primary
@Bean
public PlatformTransactionManager productionTransactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager …Run Code Online (Sandbox Code Playgroud) 我写了两个规范,如果它们的参数为 null,则返回 null。
public static Specification<Prodotto> getProdottoByLineaSpec (String linea) {
if (linea != null) {
return (root, query, criteriaBuilder) -> {
return criteriaBuilder.like((root.join("linea")).get("nome"), "%"+linea+"%");
};
}
else return null;
}
public static Specification<Prodotto> getProdottoByIngSpec (String ing) {
if (ing != null) {
return (root, query, criteriaBuilder) -> {
return criteriaBuilder.like(((root.join("listaQuoteIng")).join("ing")).get("nome"), "%"+ing+"%");
};
}
else return null;
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了第三个,将前一个与子句中的and运算符结合起来where:
public static Specification<Prodotto> getProdottoByMainTraits (String linea, String ing) {
return Specification.where(getProdottoByLineaSpec(linea).and(getProdottoByIngSpec(ing)));
}
Run Code Online (Sandbox Code Playgroud)
现在,这是有趣的部分:
ByLinea回报null,我得到一个 …我有这个作为我的查询。
select a.cust_id,a.cust_name,b.cust_id,b.cust_name
from acustomer a,bcustomer b
Run Code Online (Sandbox Code Playgroud)
DaoImp 使用 Spring NamedJdbcparameterTemplate
方法:
NamedJdbcparameterTemplate temp= new NJPT(datasource);
List<Map<String,Object>> out=temp.quertForList(query,parametermap);
Run Code Online (Sandbox Code Playgroud)
但问题是,每当我得到这个查询在数据库工具的输出,我得到4列,但在程序的输出,我只得到2列,即cust_id和cust_name的是越来越被覆盖b,由于在地图相同的键名。
我该如何解决这个问题,请注意每次查询都会有所不同,因为我将此方法用作程序的通用方法,并且输出将是值列表,因此无法为输出映射任何模型类。
请注意,我希望这个函数是通用函数,这意味着每次查询都会发生变化,并且输出将是不同类型的。
我正在开发一个微服务,它曾经有一种与其中一个列相关的 Enum,但现在我不得不改变它。
@Convert(converter = TypeEnumConverter.class)
@Enumerated(EnumType.STRING)
@Column(name = "TIPO", length = 40, nullable = false)
private TypeEnum type;
Run Code Online (Sandbox Code Playgroud)
它是这样映射的,但是枚举名称和类型不兼容,如果它不能转换回该枚举,有没有办法告诉 JPA 忽略它?
I implemented this Page request:
@GetMapping
public PageImpl<ProductFullDTO> list(@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = "10") int size) {
PageRequest pageRequest = PageRequest.of(page, size);
PageImpl<ProductFullDTO> result = productRestService.page(pageRequest);
return result;
}
public PageImpl<ProductFullDTO> page(PageRequest pageRequest){
Page<Product> pageResult = productService.findAll(pageRequest);
List<ProductFullDTO> result = pageResult
.stream()
.map(productMapper::toFullDTO)
.collect(toList());
return new PageImpl<ProductFullDTO>(result, pageRequest, pageResult.getTotalElements());
}
public Page<Product> findAll(PageRequest pageRequest) {
return this.dao.findAll(pageRequest);
}
@Repository
public interface ProductRepository extends JpaRepository<Product, Integer>, JpaSpecificationExecutor<Product> {
Page<Product> findAllByTypeIn(Pageable page, String... types); …Run Code Online (Sandbox Code Playgroud) 我在删除具有一些相关数据的实体时遇到问题。当我在我的服务中调用存储库删除方法时,我有这个异常:org.postgresql.util.PSQLException:错误:更新或删除表“表”违反外键约束......代码是这样的:
@Transactional
public void delete(Long id) {
Entity entity = repository.findById(id).orElseThrow(()->new Exception("not found"));
try {
repository.delete(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,即使我尝试捕获 Throwable 或 ConstraintViolationException,该异常也不会被 catch 块捕获。为什么这不起作用?可以做我想做的吗?
谢谢
spring-data-jpa ×10
java ×8
spring ×4
hibernate ×3
jpa ×2
spring-boot ×2
spring-data ×2
jdbctemplate ×1
jpql ×1
null ×1
spring-jdbc ×1
sql ×1
sql-server ×1