springboot与jpa的整合

在连接数据的时候使用的是h2内存数据库进行数据的查询操作,下面介绍一下内存数据库h2在springboot中的使用:

在pom.xml文件中加入依赖:

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-data-jpa

com.h2database

h2

runtime

在配置文件中添加配置:

spring.h2.console.enabled=true

在项目启动后访问http://localhost:8080/h2-console/后修改url路径为:

jdbc:h2:mem:testdb

实体类:

@Entity

public class Book {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

private Long id;

private String title;

@Column(name="READER")

private String reader;

private String isbn;

private String author;

private String description;

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getReader() {

return reader;

}

public void setReader(String reader) {

this.reader = reader;

}

public String getIsbn() {

return isbn;

}

public void setIsbn(String isbn) {

this.isbn = isbn;

}

public String getAuthor() {

return author;

}

public void setAuthor(String author) {

this.author = author;

}

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

}

DAO:

@Repository(value="bookDao")

public interface BookDao extends JpaRepository{

@Query(value="select book from Book book where book.reader = ?1")

List findByReader(String reader);


Service:

public interface BookService {

List findByReader(String reader);

}


@Service(value="bookService")

public class BookServiceImpl implements BookService{

@Autowired

BookDao BookDao;

@Override

public List findByReader(String reader) {

return BookDao.findByReader(reader);

}

}

Controller:

@RestController

public class BookController {

@Autowired

BookService BookService;

@RequestMapping(value="/findByReader",method=RequestMethod.POST)

@ResponseBody

public List findByReader(@RequestParam("reader")String reader){

System.out.println("获取到的读者是:"+reader);

List list=BookService.findByReader(reader);

System.out.println("获取到的集合的大小是:"+list.size());

return list;

}

//http://127.0.0.1:8080/findByReaderGet?reader=aa

@RequestMapping(value="/findByReaderGet",method=RequestMethod.GET)

@ResponseBody

public List findByReaderGet(@RequestParam("reader")String reader){

System.out.println("获取到的读者是:"+reader);

List list=BookService.findByReader(reader);

System.out.println("获取到的集合的大小是:"+list.size());

return list;

}

//http://127.0.0.1:8080/findByReaderByPath/aa

@RequestMapping(value="/findByReaderByPath/{reader}",method=RequestMethod.GET)

@ResponseBody

public List findByReaderByPath(@PathVariable String reader){

System.out.println("获取到的读者是:"+reader);

List list=BookService.findByReader(reader);

System.out.println("获取到的集合的大小是:"+list.size());

return list;

}

@RequestMapping("/test")

public String test(){

return "ok";

}

}

你可能感兴趣的:(springboot与jpa的整合)