又回到 jpa 的教程上了,这一篇源于某个简单的项目须要读写 db,本想着直接使用 jpa 会比较简单,然而悲催的是实际开发过程当中,发现了很多的坑;本文为错误姿式第一篇,Repository 接口没法注入问题mysql
<!-- more -->git
新开一个 jpa 项目结合 springboot 能够很方便的实现,可是在某些环境下,可能会遇到自定义的 JpaRepository 接口没法注入问题github
在 spring-boot 环境中,须要在pom.xml
文件中,指定下面两个依赖spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
接下来须要修改一下配置文件(application.properties
),指定数据库的配置信息sql
## DataSource spring.datasource.url=jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password= spring.jpa.database=MYSQL spring.jpa.hibernate.ddl-auto=none spring.jpa.show-sql=true spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
首先在 mysql 的 story 库中,新增一个表数据库
CREATE TABLE `meta_group` ( `id` int(11) NOT NULL AUTO_INCREMENT, `group` varchar(32) NOT NULL DEFAULT '' COMMENT '分组', `profile` varchar(32) NOT NULL DEFAULT '' COMMENT 'profile 目前用在应用环境 取值 dev/test/pro', `desc` varchar(64) NOT NULL DEFAULT '' COMMENT '解释说明', `deleted` int(4) NOT NULL DEFAULT '0' COMMENT '0表示有效 1表示无效', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', PRIMARY KEY (`id`), KEY `group_profile` (`group`,`profile`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='业务配置分组表';
而后定义这个表对应的 Entityspringboot
@Data @Entity @Table(name = "meta_group") public class MetaGroupPO { @Id @Column(name = "`id`") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "`group`") private String group; @Column(name = "`profile`") private String profile; @Column(name = "`desc`") private String desc; @Column(name = "`deleted`") private Integer deleted; @Column(name = "`create_time`") @CreatedDate private Timestamp createTime; @Column(name = "`update_time`") @CreatedDate private Timestamp updateTime; }
对应的 repository 接口app
public interface GroupJPARepository extends JpaRepository<MetaGroupPO, Integer> { List<MetaGroupPO> findByProfile(String profile); MetaGroupPO findByGroupAndProfileAndDeleted(String group, String profile, Integer deleted); @Modifying @Query("update MetaGroupJpaPO m set m.desc=?2 where m.id=?1") int updateDesc(int groupId, String desc); @Modifying @Query("update MetaGroupJpaPO m set m.deleted=1 where m.id=?1") int logicDeleted(int groupId); }
一个简单的数据操做封装类GroupManager
maven
@Component public class GroupManager { @Autowired private GroupJPARepository groupJPARepository; public MetaGroupPO getOnlineGroup(String group, String profile) { return groupJPARepository.findByGroupAndProfileAndDeleted(group, profile, 0); } public Integer addGroup(String group, String profile, String desc) { MetaGroupPO jpa = new MetaGroupPO(); jpa.setGroup(group); jpa.setDesc(desc); jpa.setProfile(profile); jpa.setDeleted(0); Timestamp timestamp = Timestamp.from(Instant.now()); jpa.setCreateTime(timestamp); jpa.setUpdateTime(timestamp); MetaGroupPO res = groupJPARepository.save(jpa); return res.getId(); } }
接下来重点来了,当咱们的启动类,不是在外面时,可能会出现问题;项目结构以下
咱们看一下配置类,和错误的启动应用类
@Configuration @ComponentScan("com.git.hui.boot.jpacase") public class JpaCaseAutoConfiguration { } @SpringBootApplication public class ErrorApplication { public static void main(String[] args) { SpringApplication.run(ErrorApplication.class); } }
直接启动失败,异常以下图,提示找不到GroupJPARepository
这个 bean,而这个 bean 在正常启动方式中,会由 spring 帮咱们生成一个代理类;而这里显然是没有生成了
上面的 case 可能有点极端了,通常来说项目启动类,咱们都会放在最外层;基本上不太会出现上面这种项目结构,那么分析这个 case 有毛用?
一个典型的 case
那么该怎么解决这个问题呢?
在配置类中,添加两个注解EnableJpaRepositories
与EntityScan
,并制定对应的包路径
@Configuration @EnableJpaRepositories("com.git.hui.boot.jpacase") @EntityScan("com.git.hui.boot.jpacase.entity") public class TrueJpaCaseAutoConfiguration { }
而后再次测试
@SpringBootApplication public class TrueApplication { public TrueApplication(GroupManager groupManager) { int groupId = groupManager.addGroup("true-group", "dev", "正确写入!!!"); System.out.println("add groupId: " + groupId); MetaGroupPO po = groupManager.getOnlineGroup("true-group", "dev"); System.out.println(po); } public static void main(String[] args) { SpringApplication.run(ErrorApplication.class); } }
最后小结一下,当咱们发现 jpa 方式的 Repository 没法注入时,通常是由于接口再也不咱们的扫描路径下,须要经过@EntityScan
与@EnableJpaRepositories
来额外指定
(由于篇幅问题,其余的问题拆分到其余的博文)
尽信书则不如,以上内容,纯属一家之言,因我的能力有限,不免有疏漏和错误之处,如发现 bug 或者有更好的建议,欢迎批评指正,不吝感激
下面一灰灰的我的博客,记录全部学习和工做中的博文,欢迎你们前去逛逛