SpringBoot集成Hibernate
一、环境搭建
开发工具:Spring Tool Suite v_3.9.3(简称STS)
依赖包管理(pom.xml):
<!-- 添加Web应用程序的典型依赖关系 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA框架 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Oracle数据库支持 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.1.0</version>
</dependency>
<!-- MySQL数据库支持 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.25</version>
</dependency>
配置文件
## 数据库配置
spring.datasource.driver-class-name = oracle.jdbc.driver.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@136.6.161.200:1521:orcl
spring.datasource.username = cath_thinkops
spring.datasource.password = cath_thinkops#2018
# JPA配置参数
spring.jpa.show-sql = true
spring.jpa.generate-ddl = true
# MySQL数据库配置
# spring.jpa.database=MYSQL
# 是否显示sql查询语句
# spring.jpa.show-sql=true
# spring.jpa.generate-ddl=true
# Hibernate DDL auto (create, create-drop, update)
# spring.jpa.hibernate.ddl-auto=update
# spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
# spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
数据源配置类
package com.info.conf;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@PropertySource("classpath:application.properties") // 选择配置文件的来源
public class DruidDBConfig {
@Autowired
private Environment env; // SpringBoot会把扫描过后的值放到Environment中
@Bean(name = "dataSource")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username")); // 用户名
dataSource.setPassword(env.getProperty("spring.datasource.password")); // 密码
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setInitialSize(2);
dataSource.setMaxActive(20);
dataSource.setMinIdle(0);
dataSource.setMaxWait(60000);
dataSource.setValidationQuery("SELECT 'x' from dual");
dataSource.setTestOnBorrow(false);
dataSource.setTestWhileIdle(true);
dataSource.setPoolPreparedStatements(false);
return dataSource;
}
}
二、实现
Hibernate映射实体类
package com.info.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.fasterxml.jackson.annotation.JsonFormat;
@Entity
@Table(name = "IDC_ALARM_BORD", schema = "CATH_THINKOPS")
public class AlarmBord {
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "increment")
@Column(name = "ID", unique = true, nullable = false)
private Long id;
@Column(name = "ALARM_ID")
private String alarmId;
@Column(name = "ALARM_TITLE")
@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss", timezone = "GMT+08:00") // 指定时间的格式
private String alarmTitle;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAlarmId() {
return alarmId;
}
public void setAlarmId(String alarmId) {
this.alarmId = alarmId;
}
public String getAlarmTitle() {
return alarmTitle;
}
public void setAlarmTitle(String alarmTitle) {
this.alarmTitle = alarmTitle;
}
}
DAO
package com.info.dao;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.info.entity.AlarmBord;
/**
* CrudRepository 接口继承于 Repository 接口,并新增了简单的增、删、查等方法
*
* T save(T entity); // 保存单个实体
* Iterable<T> save(Iterable<? extends T> entities); // 保存集合
* T findOne(ID id); // 根据id查找实体
* boolean exists(ID id); // 根据id判断实体是否存在
* Iterable<T> findAll(); // 查询所有实体,不用或慎用!
* long count(); // 查询实体数量
* void delete(ID id); // 根据Id删除实体
* void delete(T entity); // 删除一个实体
* void delete(Iterable<? extends T> entities); // 删除一个实体的集合
* void deleteAll(); // 删除所有实体,不用或慎用!
*/
@Repository
public interface AlarmBordDao extends CrudRepository<AlarmBord, Long> {
public List<AlarmBord> findAll();
// 支持分页查询
public Page<AlarmBord> findAll(Pageable pageable);
}
CrudRepository
和 JpaRepository
区别:
他们存在继承关系:
PagingAndSortingRepository 继承 CrudRepository
JpaRepository 继承 PagingAndSortingRepository
CrudRepository 提供基本的增删改查;PagingAndSortingRepository 提供分页和排序方法;JpaRepository 提供JPA需要的方法
Service
package com.info.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.info.dao.AlarmBordDao;
import com.info.entity.AlarmBord;
@Service
public class AlarmBordService {
@Autowired
private AlarmBordDao alarmBordDao;
// 查询所有记录
public List<AlarmBord> findAll() {
return alarmBordDao.findAll();
}
/*
* 分页查询所有记录
* page: 当前页数
* size: 查询条数
*
* Page: 是封装查询结果的对象
* List<Class<T> cls> getContent(): 获取查询结果数据
* int getTotalPages(): 获取总页数
* int getTotalElements(): 获取总数据条数
*/
public Page<AlarmBord> findAll(int page, int size) {
return alarmBordDao.findAll(buildPageRequest(page, size));
}
// 获取分页请求
private PageRequest buildPageRequest(int page, int size) {
return new PageRequest(page, size);
}
}