Springboot2 jpa 整合

springboot2 与 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

猜你喜欢

转载自blog.csdn.net/m0_37202351/article/details/82749741