Y
Y
yarushin_a2020-12-10 17:01:58
Java
yarushin_a, 2020-12-10 17:01:58

Spring + JPA how to make queries work?

Good afternoon. Requests don't work. findAll works, custom queries don't.

application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.url=jdbc:mysql://localhost:3306/ticket_system
spring.datasource.driver-class-name=org.gjt.mm.mysql.Driver
spring.datasource.username=root


Repository:
@Repository
public interface CitiesRepo extends CrudRepository<City, Integer> {
     List<City> findByName(String name);
}


Call code (The text variable is set):
List<City> cities = citiesRepo.findByName(text);

However, the request does not work and the output shows that the text variable is not substituted at the end and cities is empty:
Hibernate: select city0_.id as id1_0_, city0_.latitude as latitude2_0_, city0_.longitude as longitud3_0_, city0_.name as name4_0_, city0_.region as region5_0_ from cities city0_ where city0_.name=?


Essence:
@Entity
@Table(name = "cities")
public class City {
    @Id
    @SequenceGenerator(name="newRec", sequenceName="CITIES_SEQ",allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true,nullable = false)
    private Integer id;

    @Column(name = "name", length = 50,nullable = false)
    private String name;

    @Column(name = "region", length = 50,nullable = false)
    private String region;

    @Column(name = "latitude")
    private float latitude;

    @Column(name = "longitude")
    private float longitude;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2020-12-10
@yarushin_a

Good afternoon!
- Specify which libraries you have connected in pom.xml? In particular, the spring data jpa library is of interest
- Check if you have getters, setters and a constructor without arguments in the City class? If not, then add them.
If you have lombok connected, then you can write @Data @NoArgsConstructor
- Next, connect to your database and view the records in the database. It is possible that they are not stored in UTF-8, which is why the city is not found by name. Instead of data in the table, you will see kryakozyabry. If this problem is observed, then write

jdbc:mysql://localhost:3306/ticket_system?useUnicode=yes&characterEncoding=UTF-8

- Also pay attention to whether you have a cities table.
There is also a suspicion that you are using the word name, which is reserved in mysql, and because of this, problems may be observed. Try to escape it
@Column(name = "`name`", length = 50,nullable = false)

https://dev.mysql.com/doc/refman/8.0/en/keywords.html
https://stackoverflow.com/questions/2224503/how-to...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question