springBoot框架搭建整合jpa
1.通过 https://start.spring.io/ 选择项目需要的技术,生成响应的项目。
2.springboot启动类,配置
@ComponentScan 扫@Controller,@Service,@Repository,@Component的包路径
@EntityScan 扫@Entity的包路径
@EnableJpaRepositories 扫JPA的包路径
@SpringBootApplication @ComponentScan({"com.example.springboot.controller", "com.example.springboot.dao", "com.example.springboot.service"}) @EntityScan(basePackages = {"com.example.springboot.entity"}) @EnableJpaRepositories(basePackages = {"com.example.springboot.dao"}) public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
3. 配置applicaiton.properties
######################################################## ###datasource ######################################################## spring.datasource.url = jdbc:mysql://localhost/test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8 spring.datasource.username = root spring.datasource.password = pt891209 spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver spring.datasource.max-active=20 spring.datasource.max-idle=8 spring.datasource.min-idle=8 spring.datasource.initial-size=10 ######################################################## ### Java Persistence Api ######################################################## # Specify the DBMS spring.jpa.database = MYSQL spring.jpa.show-sql = true #jpa 可以根据entity反向创建表 spring.jpa.hibernate.ddl-auto = update #true会根据entity反向映射到数据库表中 spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy #Jpa 支持头封命名 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
4.编写controller,service
@RestController public class TestController { @Autowired private TestService testService;
@RequestMapping("/test")
List<UserEO> index(){
List<UserEO> users = testService.findUsers();
return users;
}
}
service
@Service public class TestServiceImpl implements TestService { @Autowired private UserDao userDao; @Override public List<UserEO> findUsers() { return (List)userDao.findAll(); } }
5dao层 继承
import com.example.springboot.entity.UserEO; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; public interface UserDao extends PagingAndSortingRepository<UserEO, Long>, JpaSpecificationExecutor<UserEO> { }
6.请求 http://localhost:8080/test
页面响应:
[{"id":1,"userName":null,"password":"fff","createTime":null}]