SpringBoot整合Hibernate

1、搭建简单多模块项目

具体参考我的另一篇博文IDEA搭建springBoot多模块整合Mybatis项目,其中web层的mybatis依赖去掉

2、application.properties配置

server.port=8088

spring.datasource.url = jdbc:mysql://localhost:3306/zdata?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&serverTimezone=CTT
spring.datasource.username = root
spring.datasource.password = 123456

logging.level.com.wonder = DEBUG

#Hibernate配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

具体配置项说明可参看我的另一篇博文Hibernate的各种数据库配置以及常用配置项说明

3、启动类添加支持JPA的注解

//用于扫描Dao层@Repository
@EnableJpaRepositories(basePackages = "com.xxx.xxxx")
//用于扫描JPA实体类 @Entity
@EntityScan(basePackages = "com.xxx.xxxx")

4、创建实体类

基类:

@Data
@MappedSuperclass
public class BaseObject implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;
}

子类:

@EqualsAndHashCode(callSuper = true)
@Data
@Entity
public class User extends BaseObject{
    private String userPass;
    private String userPhone;
}

5、完成Dao层数据库操作接口

public interface PlateRepository extends JpaRepository {

    @Query(value = "SELECT p FROM Plate p WHERE p.plateCode = :code AND p.status = 0")
    Plate getPlateByCode(@Param("code") String code);

    @Query(value = "SELECT binding_id FROM Plate WHERE work_order_id = :workOrderId AND status = 0 ORDER BY createdTime DESC LIMIT 1",nativeQuery = true)
    String getBindingId(@Param("workOrderId") String workOrderId);

    Integer countByBindingId(String bindingId);
}

6、完成Service和Controller(不赘述)

你可能感兴趣的:(Spring框架相关)