springBoot框架搭建整合jpa

谁借莪1个温暖的怀抱¢ 2021-12-22 13:23 456阅读 0赞

1.通过 https://start.spring.io/ 选择项目需要的技术,生成响应的项目。

2.springboot启动类,配置

  1. @ComponentScan @Controller@Service@Repository@Component的包路径
  2. @EntityScan @Entity的包路径
  3. @EnableJpaRepositories JPA的包路径
  4. @SpringBootApplication
  5. @ComponentScan({
  6. "com.example.springboot.controller", "com.example.springboot.dao", "com.example.springboot.service"})
  7. @EntityScan(basePackages = {"com.example.springboot.entity"})
  8. @EnableJpaRepositories(basePackages = {"com.example.springboot.dao"})
  9. public class SpringbootApplication {
  10. public static void main(String[] args) {
  11. SpringApplication.run(SpringbootApplication.class, args);
  12. }
  13. }
  1. 配置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  

  1. @RestController
  2. public class TestController {
  3. @Autowired
  4. private TestService testService;
  5. @RequestMapping("/test")
  6. List<UserEO> index(){
  7. List<UserEO> users = testService.findUsers();
  8. return users;
  9. }
  10. }

  service

  1. @Service
  2. public class TestServiceImpl implements TestService {
  3. @Autowired
  4. private UserDao userDao;
  5. @Override
  6. public List<UserEO> findUsers() {
  7. return (List)userDao.findAll();
  8. }
  9. }

5dao层 继承

  1. import com.example.springboot.entity.UserEO;
  2. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  3. import org.springframework.data.repository.PagingAndSortingRepository;
  4. public interface UserDao extends PagingAndSortingRepository<UserEO, Long>, JpaSpecificationExecutor<UserEO> {
  5. }

  

 6.请求 http://localhost:8080/test

页面响应:

  1. [{"id":1,"userName":null,"password":"fff","createTime":null}]

转载于:https://www.cnblogs.com/ptcnblog/p/10971856.html

发表评论

表情:
评论列表 (有 0 条评论,456人围观)

还没有评论,来说两句吧...

相关阅读