Springboot jpa 整合

  1. pom.xml 添加 mysql 和 jpa 等依賴。

  2. application.yml:添加數據庫連接信息(默認使用hikari高性能連接池)

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false
    username: root
    password: root
  jpa:
    hibernate:
      # create:drop and create,會刪除原內容,危險
      # create-drop:關閉程序後刪除表,危險
      # update:不刪除數據,只更改表結構
      # none:什麼都不做
      # validate:驗證entity和 表結構,不一致報錯
      ddl-auto: validate
  1. 添加 entity 實體類(數據庫需創建對應表或使用hibernate自動生成),JsonIgnoreProperties註解:避免hibernate懶加載與jackson衝突
@Entity
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler"})
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    public Long getId() { return id; }
    public String getName() { return name; }
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
}
  1. 新建 repository 接口
public interface UserRepository extends JpaRepository<User, Long> {
    public List<User> findByName(String name);
}
  1. 添加 service ,注入 repository
@Service
public class UserService {
	@Autowired UserRepository userRepository;

	public List<User> findByName(String name) {
        return userRepository.findByName(name);
    }
}

參考:http://www.fengyunxiao.cn

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章