2.6 KiB
2.6 KiB
Extras telusko
- for configuring h2 database(in memory database)
- make sure package is there in pom.xml
- add following in
application.properties
here telusko is name of databasespring.h2.console.enabled=true spring.datasource.platform=h2 spring.datasource.url=jdbc:h2:mem:telusko - now start your application and go to
localhost:8080/h2~consoleand u will get a login page. now click on test connection button
- for configuring JPA
- make sure respective dependency is there and at
application.propertiesalong with spring.datasource properties one more is mentioned for say mysqlspring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect - in POJO add annotation
Entityabove class defintion and in instance sayaidadd@Idannotation - now a table with fields of those POJO instance name will be created
- u can add
data.sqlinsrc/main/resourcesto add initial data - in order to do crud operations use CrudRepository which is a part of spring data commons which is part of JPA
- Create this interface
and then in your main file/controller to save data usepackage com.example.demo; import org.springframework.data.repository.CrudRepository; public interface AlienRepo extends CrudRepository<Other,Integer> { }public class HomeController(){ @Autowire Alienrepo repo; @RequestMapping("/addAlien") public String addAlien(Alien alien){ repo.save(alien); return "home"; } @RequestMapping("/getAlien") public ModelAndView getAlien(@RequestParam int aid){ ModelAndView mv= new ModelAndView("showAlien"); Alien alien=repo.findById(aid).orElse(new Alien()); mv.addObject(alien); return mv; } } - make sure respective dependency is there and at
- More query methods for interface Repo
- In the following code, these other query methods are defined by just declaring then by following certain conventions like
findBy<PropertyName><Operation>here property like Tech,Aid(first letter must be capital and other as small) - everything is not configured with conventions so for complex queries
Queryannotation have to be used.?1is used instead of?bcz there can be other placeholders too and its to index them.
package com.example.demo; import org.springframework.data.repository.CrudRepository; public interface AlienRepo extends CrudRepository<Other,Integer> { List<Alien> findByTech(String tech); List<Alien> findByAidGreaterThan(int aid); // jpql instead of sql @Query("from Alien where tech=?1 order by aname") List<Alien> findByTechSorted(String tech); } - In the following code, these other query methods are defined by just declaring then by following certain conventions like