spring 如何使用Sping Boot 3.2.0与MySQL数据库和JpaRepository @Query进行布尔比较

jc3wubiy  于 12个月前  发布在  Spring
关注(0)|答案(2)|浏览(148)

我正计划将Sping Boot 从2.7.1迁移到3.2.0。
这是我的模特课

@Entity
@Table(name = "tutorials")
public class Tutorial {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    @Column(name = "published")
    private Boolean published;

    // setters and getters
}

字符串
我的存储库:

public interface TutorialRepository extends JpaRepository<Tutorial, Long> {     
    @Query("select t from Tutorial t where t.published IS TRUE")
    List<Tutorial> getTutorial();
}


和我的休息控制器:

@RestController
@RequestMapping("/api")
public class TutorialController {

@Autowired
TutorialRepository tutorialRepository;

@GetMapping("/tutorials")
public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
    try {
        List<Tutorial> tutorials = new ArrayList<Tutorial>();

        if (title == null)
            tutorialRepository.findAll().forEach(tutorials::add);
        else
            tutorialRepository.findByTitleContaining(title).forEach(tutorials::add);

        if (tutorials.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }

        return new ResponseEntity<>(tutorials, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

@GetMapping("/tutorial/published")
public ResponseEntity<List<Tutorial>> findByTutorialPublished() {
    try {
        List<Tutorial> tutorials = tutorialRepository.getTutorial();
        tutorials.forEach(System.out::println);
        if (tutorials.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(tutorials, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

}


对于数据库配置,我创建了application.properties

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost/testdb
spring.datasource.username=root
spring.datasource.password=root


当我检查API 'http://localhost:8080/api/tutorial/published'时,得到500个内部服务器错误。这意味着,无法执行带有布尔比较的JPA查询。但它在spring Boot 2.7.1中工作。
我再次尝试在pom.xml中使用hib到6.4.0。

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
        <relativePath />
    </parent>
    <groupId>com.bezkoder</groupId>
    <artifactId>spring-mysql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-mysql</name>
    <description>Demo project for Spring Boot Apis CRUD using Spring Data JPA</description>

<properties>
    <java.version>21</java.version>
    <hibernate.version>6.4.0.Final</hibernate.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>


没希望了。
在Eclipse IDE中,我可以看到以下警告:(没有问题)

ANTLR Tool version 4.10.1 used for code generation does not match the current runtime version 4.13.0
ANTLR Runtime version 4.10.1 used for parser compilation does not match the current runtime version 4.13.0


但在eclipse中测试API时出现的错误如下:

org.springframework.dao.InvalidDataAccessApiUsageException: org.springframework.data.jpa.repository.query.BadJpqlGrammarException: Line 1:44 mismatched input 'IS' expecting {<EOF>, ',', '+', '-', '/', '||', '[', '.', AND, '*', BY, DAY, EPOCH, EXCEPT, GROUP, HOUR, INTERSECT, MINUTE, MONTH, NANOSECOND, OR, ORDER, QUARTER, SECOND, UNION, WEEK, YEAR}; Bad JPQL grammar [select t from Tutorial t where t.published IS TRUE]


请引导我继续与Sping Boot 3.2.0?

pod7payv

pod7payv1#

您可以使用JPA查询方法,如在您的案例中的findByPublishedTrue(),以便将方法名称转换为JPA查询。

public interface TutorialRepository extends JpaRepository<Tutorial, Long> {     
    List<Tutorial> findByPublishedTrue();
}

字符串

**注意:**你不必在你的方法上使用@Query

如果你想了解更多关于JPA查询方法的信息,请查看官方文档-https://docs.spring.io/spring-data/jpa/reference/jpa/query-methods.html

kulphzqa

kulphzqa2#

查看https://docs.spring.io/spring-data/jpa/docs/current-SNAPSHOT/reference/html/#jpa.query-methods.query-creation的查询语法。您得到的错误“Bad JPQL grammar[select t from pixel t where t.published IS TRUE]”明确表示JPA查询语法不正确。
此外,<hibernate.version>6.4.0.Final</hibernate.version>不会随spring Boot 3.2.0默认使用,因此警告是因为用于编译和运行hibernate查询的版本不正确而出现的。删除它以使用spring Boot 3.2.0附带的默认hibernate版本来解决此警告

相关问题