SpringBoot入门系列之JPA mysql
一,准备工作,建立spring-boot-sample-mysql工程
1、http://start.spring.io/
A、Artifact中输入spring-boot-sample-MySQL
B、勾选Web下的web
C、勾选SQL下的JPAMYSQL
2、Eclips中导入工程spring-boot-sample-mysql
A、解压快捷工程spring-boot-sample-mysql到某文件夹
B、eclips中file->import->ImportExistingMavenProjects-->SelectMavenprojects-->finish导入工程
3、工程导入之后,文件结构如下图
4、在包com.example下建立web文件夹
5、便于测试,引入spring-boot-sample-helloworld的HelloController及配置文件logback.xml
HelloController代码为
packagecom.example.web;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
@RestController
publicclassHelloController{
protectedstaticLoggerlogger=LoggerFactory.getLogger(HelloController.class);
@RequestMapping("/")
publicStringhelloworld(){
logger.debug("访问hello");
return"Helloworld!";
}
@RequestMapping("/hello/{name}")
publicStringhelloName(@PathVariableStringname){
logger.debug("访问helloName,Name={}",name);
return"Hello"+name;
}
}
logback.xml配置为
%d%p(%file:%line\)-%m%n GBK log/base.log log/base.log.%d.i% 64MB %d%p(%file:%line\)-%m%n UTF-8
注:logback.xml文件位于src/main/resources下
6、启动工程,通过浏览器查看正确性
http://localhost:8080/
http://localhost:8080/hello/上帝
二,使用JPA,构建业务对象及访问库
1、在包com.example下建立domain文件夹
2、在domain中建立类Person
packagecom.example.domain;
importjavax.persistence.Entity;
importjavax.persistence.GeneratedValue;
importjavax.persistence.Id;
@Entity
publicclassPerson{
@Id
@GeneratedValue
privateLongid;
privateStringname;
privateIntegerage;
privateStringaddress;
publicPerson(){
super();
}
publicPerson(Longid,Stringname,Integerage,Stringaddress){
super();
this.id=id;
this.name=name;
this.age=age;
this.address=address;
}
publicLonggetId(){
returnid;
}
publicvoidsetId(Longid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicIntegergetAge(){
returnage;
}
publicvoidsetAge(Integerage){
this.age=age;
}
publicStringgetAddress(){
returnaddress;
}
publicvoidsetAddress(Stringaddress){
this.address=address;
}
}
注意:构造函数
3、在包com.example下建立repository文件夹
4、在repository中建立接口PersonRepository
packagecom.example.repository; importjava.util.List; importorg.springframework.data.jpa.repository.JpaRepository; importorg.springframework.data.jpa.repository.Query; importorg.springframework.data.repository.query.Param; importorg.springframework.stereotype.Repository; importcom.example.domain.Person; @Repository publicinterfacePersonRepositoryextendsJpaRepository{ List findByName(Stringname); List findByAddress(Stringaddress); List findByNameAndAddress(Stringname,Stringaddress); @Query("selectpfromPersonpwherep.name=:nameandp.address=:address") List withNameAndAddressQuery(@Param("name")StringName,@Param("address")Stringaddress); }
5、在web中建立DataController
packagecom.example.web;
importjava.util.List;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.data.domain.Page;
importorg.springframework.data.domain.PageRequest;
importorg.springframework.data.domain.Sort;
importorg.springframework.data.domain.Sort.Direction;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
importcom.example.domain.Person;
importcom.example.repository.PersonRepository;
@RestController
publicclassDataController{
protectedstaticLoggerlogger=LoggerFactory.getLogger(DataController.class);
@Autowired
PersonRepositorypersonRepository;
@RequestMapping("/save")
publicPersonsave(Stringname,Stringaddress,Integerage){
logger.debug("save开始");
Personp=personRepository.save(newPerson(null,name,age,address));
logger.debug("save结束");
returnp;
}
@RequestMapping("/q1")
publicListq1(Stringaddress){
logger.debug("q1开始");
logger.debug("q1接收参数address={}",address);
Listpeople=personRepository.findByAddress(address);
returnpeople;
}
@RequestMapping("/q2")
publicListq2(Stringname,Stringaddress){
logger.debug("q2开始");
logger.debug("q2接收参数name={},address={}",name,address);
returnpersonRepository.findByNameAndAddress(name,address);
}
@RequestMapping("/q3")
publicListq3(Stringname,Stringaddress){
logger.debug("q3开始");
logger.debug("q3接收参数name={},address={}",name,address);
returnpersonRepository.withNameAndAddressQuery(name,address);
}
@RequestMapping("/sort")
publicListsort(){
logger.debug("sort开始");
Listpeople=personRepository.findAll(newSort(Direction.ASC,"age"));
returnpeople;
}
@RequestMapping("/page")
publicPagepage(){
logger.debug("page开始");
Pagepeople=personRepository.findAll(newPageRequest(1,2));
returnpeople;
}
}
6、配置数据库连接,在application.properties(src/main/resources下)
spring.datasource.url=jdbc:mysql://192.168.56.201:3306/bootsample?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jackson.serialization.indent_output=true
7、运行测试
A、先保存数据
http://localhost:8080/save?name=aa&&address=北京&&age=1
http://localhost:8080/save?name=ab&&address=北京&&age=2
http://localhost:8080/save?name=cq1&&address=重庆&&age=50
http://localhost:8080/save?name=cq2&&address=重庆&&age=51
B、查询q1
http://localhost:8080/q1?address=北京
C、查询q2
http://localhost:8080/q2?address=北京&&name=aa
D、查询q3
http://localhost:8080/q3?address=北京&&name=aa
E、排序
http://localhost:8080/sort
F、分页
http://localhost:8080/page
运用hibernate访问mysql,基本也是老技术,只是用JPA简化了dao层代码,对于业务对象基本没有变化。
以上所述是小编给大家介绍的SpringBoot入门系列之JPAmysql,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!