如何解决从MySQL数据库检索最近记录数时Spring Boot / Hibernate出现问题
我正在userRepository中使用以下查询来获取最近一个月从MysqL创建的最近记录
@Query("select count(*) from User user where user.created_on > date_add(Now(),interval -1 month)")
但是我遇到了以下错误。
antlr.MismatchedTokenException: expecting CLOSE,found 'month'
at antlr.Parser.match(Parser.java:211) ~[antlr-2.7.7.jar:na]
antlr.MismatchedTokenException: expecting EOF,found ')'
at antlr.Parser.match(Parser.java:211) ~[antlr-2.7.7.jar:na]
如何解决此问题?
解决方法
嗨,在这种情况下,我将反对使用jpql / sql查询。这就是我做到的方式。创建存储库,并使用方法findAllByCreatedOnBetween
将当前日期和上个月作为日期对象传递,因此基本上可以选择给定日期之间的所有行。
这是hibernate生成的sql
生成的SQL:
select user0_.id as id1_20_,user0_.created_on as created_2_20_,user0_.name as name3_20_ from user user0_ where user0_.created_on between ? and ?
实体类User.java
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.util.Date;
import java.util.UUID;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
@Type(type = "uuid-char")
private UUID id;
private String name;
@Temporal(value = TemporalType.DATE)
private Date createdOn;
public UUID getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
}
存储库
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Repository
public interface UserRepository extends JpaRepository<User,UUID> {
List<User> findAllByCreatedOnBetween(Date lastMonth,Date currentMonth);
}
单元测试
import in.silentsudo.hibernatetips.TestApplication;
import in.silentsudo.hibernatetips.domain.User;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@ExtendWith(SpringExtension.class)
@Transactional
@SpringBootTest(classes = TestApplication.class)
class UserCreatedInLastMonth {
@Autowired
private UserRepository userRepository;
@Test
void testUserCreatedLastMonth() {
User silentSudo = new User();
silentSudo.setName("silentsudo");
silentSudo.setCreatedOn(getCreatedDate(5,Calendar.JULY,2019));
userRepository.save(silentSudo);
Assertions.assertNotNull(silentSudo.getId());
User randomUser = new User();
randomUser.setName("random-user");
randomUser.setCreatedOn(getCreatedDate(1,Calendar.OCTOBER,2020));
userRepository.save(randomUser);
Assertions.assertNotNull(randomUser.getId());
//Current Calendar
Calendar currentCalendar = Calendar.getInstance();
Date today = currentCalendar.getTime();
//A month before
currentCalendar.add(Calendar.MONTH,-1);
Date monthBefore = currentCalendar.getTime();
Assertions.assertTrue(today.after(monthBefore));
List<User> allUserInLastMonth = userRepository.findAllByCreatedOnBetween(monthBefore,today);
Assertions.assertEquals(1,allUserInLastMonth.size());
}
private Date getCreatedDate(int day,int month,int year) {
Calendar createdDate = Calendar.getInstance();
createdDate.set(Calendar.DAY_OF_MONTH,day);
createdDate.set(Calendar.MONTH,month);
createdDate.set(Calendar.YEAR,year);
return createdDate.getTime();
}
}
,
您正在使用JPQL,因为默认情况下它与@Query注释一起使用。 通过以下方式启用本机SQL查询:
@Query(nativeQuery = true,value = "select count(*) from User user where user.created_on > date_add(now(),interval -1 month)"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。