我使用Spring data了我的项目,我使用的是标准的Repository那extends CRUD Repository.
我的代码按预期工作,但是当我调用repository.save()数据库时没有改变?
我是否还需要commit在此之后调用一个以便更改数据库?或者该repository.save()方法是否应自动更改数据库?
我在Spring Jpa Data 文档中阅读了关于两个不同类型的对象的信息,这些文档是在您对存储库进行动态查询时进行的.
页面和切片
Page<User> findByLastname(String lastname, Pageable pageable);
Slice<User> findByLastname(String lastname, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)
所以,我试图找到一些文章或任何关于主要差异和两者的不同用法,性能如何变化以及排序如何影响两种类型的查询.
有没有人有这种类型的知识,文章或一些好的信息来源?
我有一个简单的实体.我正在使用spring-data-jpa版本1.2.0.RELEASE和eclipselink 2.4.1.
@Entity
@Table(name="platform")
public class Platform {
@Id
@Column(name="id", nullable=false, updatable=false, insertable=true)
private Long id;
// etc.
}
Run Code Online (Sandbox Code Playgroud)
我想保存它.我的存储库看起来像
public interface PlatformRepository extends JpaRepository<Platform, Long> {
Platform findByName( String name );
}
Run Code Online (Sandbox Code Playgroud)
使用此方法,我的控制器非常简单
@RequestMapping(method=RequestMethod.POST, produces="application/json")
public Platform post( Platform platform ) {
Platform result = platformDao.saveAndFlush(platform);
return result;
}
Run Code Online (Sandbox Code Playgroud)
而这种方法的反应是
{"platform":{"id":null,"name":"Test1"}}
Run Code Online (Sandbox Code Playgroud)
从平台中选择*显示Test1的ID为6.该表定义为:
create table platform(
id int not null auto_increment primary key,
name varchar(128) not null);
Run Code Online (Sandbox Code Playgroud)
我希望在保存后设置ID,但事实并非如此.他们在编写实体后不会期望我立即进行查找,对吧?
@Repository
public interface LoginDao extends JpaRepository<LoginEntity, Integer> { //}, LoginDaoCustom {
LoginEntity findByLogin(String login);
@Modifying
int changePassword(String password, String login);
}
Run Code Online (Sandbox Code Playgroud)
如果我将changePassword的返回值更改为int以外的任何值,我会得到以下错误.
Caused by: java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type!
at org.springframework.util.Assert.isTrue(Assert.java:65)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.<init>(JpaQueryExecution.java:166)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.getExecution(AbstractJpaQuery.java:106)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:86)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:337)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
... 46 more
Run Code Online (Sandbox Code Playgroud)
这个整数返回值是什么意思?我确信春天有记录在某处,但我找不到它.它未列在jpa.modifying-queries中
我应该补充一点,如果将返回类型声明为int,则更新将以静默方式失败,并且不会更新值.
使用Spring Data nad Querydsl,我们可以声明存储库接口并跳过实现类.一些具有特定名称或使用@Query注释的方法,这就是全部.
但是有时候我想使用JPAQuery并自己定义方法的主体,比方说
@Repository
public class MyRepositoryImpl implements MyRepository {
@PersistenceContext
private EntityManager em;
@Override
public List<Tuple> someMethod(String arg) {
JPAQuery query = new JPAQuery(em);
...
}
Run Code Online (Sandbox Code Playgroud)
但这样我就必须实现其他MyRepository接口方法,这会破坏Spring Data的所有优点!
我可以看到两个选项:
我更喜欢选项#2,但据我所知,在@Service类中我们应该只调用存储库方法,所以它也不是一个完美的解决方案.
那么程序员如何处理呢?
是否可以获取用户定义范围内的数据[int starting record -int last record]?
在我的情况下,用户将在查询字符串中定义他想要获取数据的范围.我尝试过这样的事情
Pageable pageable = new PageRequest(0, 10);
Page<Project> list = projectRepository.findAll(spec, pageable);
Run Code Online (Sandbox Code Playgroud)
spec是我定义的规范,但不幸的是,这没有帮助.可能是我在这里做错了.
我见过其他spring jpa提供的方法,但没有什么帮助.
用户可以输入类似localhost:8080/Section/employee的内容吗?范围{ "COLUMNNAME":名称 "从":6, "到":20}
所以这表示获取员工数据并且它将获取前15条记录(按columnName排序)并不重要.
如果你能给我一些更好的建议,如果你认为我没有提供足够的信息请告诉我,我会提供所需的信息.
更新:我不想使用本机或创建查询语句(直到我没有任何其他选项).可能是这样的:
Pageable pageable = new PageRequest(0, 10);
Page<Project> list = projectRepository.findAll(spec, new pageable(int startIndex,int endIndex){
// here my logic.
});
Run Code Online (Sandbox Code Playgroud)
如果你有更好的选择,你也可以建议我.
谢谢.
我想知道是否有一种机制可以将超过1000个项目的集合处理到Spring Repository中以获取SQL IN子句.现在,我们在将项目列表传递到存储库之前拆分项目列表,但是如果驱动程序或弹簧知道Oracle的限制,那将会很好,并且会为我们工作.
我使用Spring Boot和Data Rest在Java8中创建一个简单的微服务并获得postgres异常.
我的实体:
@Entity
public class ArchivedInvoice implements Serializable {
...
@Column
private String invoiceNumber;
@Column
private java.sql.Date invoiceDate;
...
}
Run Code Online (Sandbox Code Playgroud)
我的存储库界面:
@RepositoryRestResource(collectionResourceRel = "archivedinvoices", path = "archivedinvoices")
public interface ArchivedInvoiceRepository extends PagingAndSortingRepository < ArchivedInvoice, Long > {
...
@RestResource(rel = "findByXYZ", path = "findByXYZ")
@Query(value = "SELECT ai FROM #{#entityName} ai WHERE "
+ "(:invoiceNumber IS NULL OR ai.invoiceNumber LIKE :invoiceNumber) AND "
+ "(:invoiceDate IS NULL OR ai.invoiceDate = :invoiceDate)"
)
public Page < ArchivedInvoice > findByXYZ( …Run Code Online (Sandbox Code Playgroud) 我知道之前已经回答了类似的问题,但是我的问题是在接口中使用r 3方法实现save更新.我目前正在我的项目中使用以下方法.不知道在这里制作saveorUpdate.在我的课程之后:
public interface CompanyRepository extends CrudRepository<Company,Long>{
Company findByCompanyName (String companyName);
List<Company> findAll();
Company findById(Long id);
}
Run Code Online (Sandbox Code Playgroud)
以下是我公司类的一部分
@Entity
public class Company extends BaseEntity{
@NotNull
@Size(min = 2, max = 16)
private String companyName;
@Length(max = 60)
private String desc;
//TODO max: add LOGO class later for pic saving
@OneToMany
private List<MobileModel> mobileModels;
public Company()
{
super();
mobileModels = new ArrayList<>();
}
//Getters n setters
}
Run Code Online (Sandbox Code Playgroud)
以下是我的baseEntity clas
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected final …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Spring Boot 项目中加载 application.properties 进行测试。我正在使用 @DataJpaAnnotation 以及我的自定义 application.properties 文件。
这是我的示例配置如下
@DataJpaTest
@RunWith(SpringRunner.class)
@SqlGroup({
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {
"classpath:sql/dont-use-cascadeType-remove/before.sql" }),
@Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = {
"classpath:sql/dont-use-cascadeType-remove/after.sql" }) })
@TestPropertySource(locations = { "classpath:application.properties" })
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@Slf4j
public class BookCategoryRepositoryTest {
Run Code Online (Sandbox Code Playgroud)
我能够成功执行测试用例,但是当我验证日志时,我的应用程序正在采用嵌入的 H2 Db URL,而不是我在 application.properties 文件中提到的 URL。
从我发现的日志中
embedded database: url='jdbc:h2:mem:69b49362-3f83-4e79-9f35-b0deb5e744f2;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
Run Code Online (Sandbox Code Playgroud)
我的属性文件包含
spring.datasource.url=jdbc:p6spy:mem:jpa-best-practices;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=db-user
spring.datasource.password=db-password
Run Code Online (Sandbox Code Playgroud)
不知道为什么会发生这种情况,我无法找到解决方案。请帮忙。
spring spring-data spring-data-jpa spring-boot spring-boot-test
spring-data ×10
spring ×8
java ×5
spring-boot ×2
hibernate ×1
jpa ×1
oracle ×1
postgresql ×1
querydsl ×1
repository ×1
spring-mvc ×1