springBoot + JPA整合

一 :加入依賴

二 :配置.properties文件

三 :代碼實現

四 :啓動配置

五 :總結


一:加入依賴

        本依賴實在基礎springBoot的依賴上添加

 <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 配置

spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.tomcat.max-active=100
spring.datasource.tomcat.max-idle=200
spring.datasource.tomcat.initialSize=20
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect

三 代碼:

    實體類如下:

      @Entity會被spring掃描並加載,
      @Id註解在主鍵上
     @Column name="name" 指該字段對應的數據庫的字段名,如果相同就不需要定義。數據庫下劃線間隔和代碼中的駝峯法       視爲相同。

@Entity
public class User implements Serializable {
   
   @Id
   @GeneratedValue
   //@ApiModelProperty(name = "ID", value = "用戶ID", dataType = "Long")
   public long id;
   @Column(name = "name")
   //@ApiModelProperty(name = "name", value = "用戶名", dataType = "String")
   public String name;
   //@ApiModelProperty(name = "name", value = "用戶名", dataType = "String")
   public String phone;

}

Repository如下:

@Repository
@Transactional
public interface UserRepos extends JpaRepository<User, Long> {
    /**
     * 通過用戶名相等查詢
     *
     * @param name 用戶名
     * @return
     */
    List<User> findByName(String name);
    /**
     * 通過名字like查詢
     *
     * @param name 用戶名
     * @return
     */
    List<User> findByNameLike(String name);
}

調用如下:

@Service
public class UserServiceImple  implements IUserService,Serializable {

    @Autowired
    private UserRepos userRepos;

    public List<User> JPA_findAll() {
        return userRepos.findAll();
    

}

啓動配置

    

  @EnableJpaRepositories({"test.repository"})//掃描repository
  @EntityScan("test.**")//掃描實體
@ComponentScan(basePackages ="test.**")//掃描bean

總結:

      1.如果項目中添加了JPA的依賴,但是沒有配置數據源,啓動項目會拋出異常。

        解決方式: 排除啓動加載

    @SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})//TODO 啓動 排除JPA和DATASourc
    2. spring boot 默認掃描類是 在啓動類的當前包和下級包,如果不在默認掃描範圍內,則需要添加註解掃描對應路徑。否則無法掃描到controller,service等一些bean。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章