I'm learning spring 5 MVC with spring data JPA and sql queries
I'm trying to use a native query in my spring api restful example but when I run the project, my method returns an empty json object.
My Model class
@Entity
@Table(name = "bicycle")
public class Bicycle
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name="name")
private String name;
@Column(name="year")
private int year;
}
My repository class
@Repository
public interface BicycleRepository extends CrudRepository<Bicycle, Long>
{
@Query(value = "SELECT * from db_bicycles.bicycle", nativeQuery = true)
public List<Bicycle> obtenerTodos();
}
My controller class
@RestController
@RequestMapping("/api")
public class BicycleController
{
@Autowired
private BicycleRepository bicycleRepository;
//create get all bicycles
@GetMapping("/bicycles")
public List<Bicycle> getAllBicycles()
{
return bicycleRepository.obtenerTodos();
}
}
My application properties
spring.datasource.url=jdbc:mysql://localhost/db_bicycles?useUnicode=true&useJDBCCompilantTimeZoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
This table have 2 rows.
use getter/setter in your POJO class
you need not to write query to retrieve all record. Simply you can make use of findAll() method which is available in crudeRepository.
bicycleRepository.findAll();
(will return list of your POJO class.)
Injection to populate data. OR you can make a POST call to populate data in table using save() method.
If you are using lombok and Spring Tools Suite in your project, then try running Maven Clean and Maven Install.
mvn clean install
After that, you can run the project. It should work.
The solution is to add the getter and setters, eclipse (STS) only add me the setters
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.