71 lines
2.6 KiB
Markdown
71 lines
2.6 KiB
Markdown
Extras telusko
|
|
|
|
- for configuring h2 database(in memory database)
|
|
- make sure package is there in pom.xml
|
|
- add following in `application.properties`
|
|
```yml
|
|
spring.h2.console.enabled=true
|
|
spring.datasource.platform=h2
|
|
spring.datasource.url=jdbc:h2:mem:telusko
|
|
```
|
|
here telusko is name of database
|
|
- now start your application and go to `localhost:8080/h2~console` and u will get a login page. now click on test connection button
|
|
- for configuring JPA
|
|
- make sure respective dependency is there and at `application.properties` along with spring.datasource properties one more is mentioned for say mysql
|
|
`spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect`
|
|
- in POJO add annotation `Entity` above class defintion and in instance say `aid` add `@Id` annotation
|
|
- now a table with fields of those POJO instance name will be created
|
|
- u can add `data.sql` in `src/main/resources` to 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
|
|
```java
|
|
package com.example.demo;
|
|
|
|
import org.springframework.data.repository.CrudRepository;
|
|
|
|
public interface AlienRepo extends CrudRepository<Other,Integer> {
|
|
|
|
|
|
}
|
|
|
|
```
|
|
and then in your main file/controller to save data use
|
|
```java
|
|
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;
|
|
}
|
|
}
|
|
```
|
|
- 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 `Query` annotation have to be used. `?1` is used instead of `?` bcz there can be other placeholders too and its to index them.
|
|
```java
|
|
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);
|
|
}
|
|
```
|