亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot怎么整合spring-data-jpa

發布時間:2020-06-26 00:55:12 來源:億速云 閱讀:369 作者:Leah 欄目:開發技術

本篇文章給大家分享的是有關SpringBoot整合spring-data-jpa的方法,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

jpa是JavaEE定義的一種規范,常用的實現一般是Hibernate,而spring-data-jpa則是對jpa的又一層封裝,提供了更多便捷的方法。

導入依賴

<dependency>
	<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

配置

spring:
 data:
 jpa:
  repositories:
  # 開啟jpa
  enabled: true
  bootstrap-mode: default
 jpa:
 # 數據庫方言
 database-platform: org.hibernate.dialect.MySQL57Dialect
 open-in-view: false
 # 打印SQL
 show-sql: false
 properties:
  # 格式化輸出的SQL語句
  hibernate.format_sql: false
 hibernate:
  # 自動建表策略
  ddl-auto: update

這里忽略了數據源的配置

關于自動建表策略

# 枚舉值
spring.jpa.hibernate.ddl-auto
create				不管表是否存在, 每次啟動都會重新建表(會導致數據丟失)
create-drop			啟動的時候創建表, 程序退出(SessionFactory關閉)的時候刪除表
none				不進行任何操作
update				如果數據表不存在則創建, 在實體對象被修改后,下次啟動重新修改表結構(不會刪除已經存在的數據)
validate			啟動的時候驗證數據表的結構, 

相關的配置類

這里僅僅列出了部分常用的配置,如果需要了解所有的配置信息,可以參考配置類

JpaProperties
SpringDataWebProperties
HibernateProperties

相關配置的文檔docs.spring.io/spring-boot…

定義實體類User

import java.io.Serializable;
import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;

// 指定表名稱
@Table(name = "user", indexes = {
	// 定義索引
	@Index(columnList = "account", unique = true) 
})
// 標識實體類
@Entity
// 設置表注釋
@org.hibernate.annotations.Table(appliesTo = "user", comment = "用戶")
public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4953012795378725917L;

	@Id // id 字段
	@Column(columnDefinition = "INT(11) UNSIGNED COMMENT 'id'")
	@GeneratedValue(strategy = GenerationType.IDENTITY) // 自增
	private Integer id;

	// 賬戶
	@Column(columnDefinition = "VARCHAR(50) COMMENT '登錄賬戶'", nullable = false)
	private String account;

	// 密碼
	@Column(columnDefinition = "VARCHAR(255) COMMENT '登錄密碼'", nullable = false)
	private String password;

	// 性別
	@Column(columnDefinition = "TINYINT(1) COMMENT '性別。0:男,1:女'", nullable = false)
	@Enumerated
	private Gender gender;

	// 創建時間
	@Column(name = "created_date", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間'", nullable = false)
	private LocalDateTime createdDate;

	// 最后修改時間
	@Column(name = "last_modified_date", columnDefinition = "timestamp NULL DEFAULT NULL COMMENT '最后一次修改時間'")
	private LocalDateTime lastModifiedDate;

	// 記錄狀態
	@Column(columnDefinition = "TINYINT(1) unsigned COMMENT '是否啟用'", nullable = false)
	private Boolean enabled;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Gender getGender() {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	public LocalDateTime getCreatedDate() {
		return createdDate;
	}

	public void setCreatedDate(LocalDateTime createdDate) {
		this.createdDate = createdDate;
	}

	public LocalDateTime getLastModifiedDate() {
		return lastModifiedDate;
	}

	public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
		this.lastModifiedDate = lastModifiedDate;
	}

	public Boolean getEnabled() {
		return enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", account=" + account + ", password=" + password + ", gender=" + gender
				+ ", createdDate=" + createdDate + ", lastModifiedDate=" + lastModifiedDate + ", enabled=" + enabled
				+ "]";
	}

	public static enum Gender {
		BOY, GIRL
	}
}

Repository

抽象出BaseRepository

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;

@NoRepositoryBean // 該接口不是一個Repository,不需要生成代理實現
public interface BaseRepository <T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor <T>							// , QuerydslPredicateExecutor<T> 如果使用了QueryDSL還可以實現這個接口
{

}

定義 UserRepository

import io.springboot.jpa.entity.User;

public interface UserRepository extends BaseRepository<User, Integer> {

}

Service

抽象出 BaseService

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface BaseService<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor <T>
														// , QuerydslPredicateExecutor<T> 
{

}

抽象出 AbstractService

import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import io.springboot.jpa.repository.BaseRepository;
public abstract class AbstractService<T, ID> implements BaseService <T, ID> {
	/**
	 * 泛型注入
	 */
	@Autowired
	protected BaseRepository<T, ID> baseRepository;
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll() {
		return this.baseRepository.findAll();
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll(Sort sort) {
		return this.baseRepository.findAll(sort);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAllById(Iterable<ID> ids) {
		return this.baseRepository.findAllById(ids);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public <S extends T> List<S> saveAll(Iterable<S> entities) {
		return this.baseRepository.saveAll(entities);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void flush() {
		this.baseRepository.flush();
	}
	@Transactional(rollbackFor = Throwable.class)
	public <S extends T> S saveAndFlush(S entity) {
		return this.baseRepository.saveAndFlush(entity);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteInBatch(Iterable<T> entities) {
		this.baseRepository.deleteInBatch(entities);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteAllInBatch() {
		this.baseRepository.deleteAllInBatch();
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public T getOne(ID id) {
		return this.baseRepository.getOne(id);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> List<S> findAll(Example<S> example) {
		return this.baseRepository.findAll(example);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> List<S> findAll(Example<S> example, Sort sort) {
		return this.baseRepository.findAll(example, sort);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Page<T> findAll(Pageable pageable) {
		return this.baseRepository.findAll(pageable);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public <S extends T> S save(S entity) {
		return this.baseRepository.save(entity);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Optional<T> findById(ID id) {
		return this.baseRepository.findById(id);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public boolean existsById(ID id) {
		return this.baseRepository.existsById(id);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public long count() {
		return this.baseRepository.count();
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteById(ID id) {
		this.baseRepository.deleteById(id);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void delete(T entity) {
		this.baseRepository.delete(entity);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteAll(Iterable<&#63; extends T> entities) {
		this.baseRepository.deleteAll(entities);
	}
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteAll() {
		this.baseRepository.deleteAll();
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> Optional<S> findOne(Example<S> example) {
		return this.baseRepository.findOne(example);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) {
		return this.baseRepository.findAll(example, pageable);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> long count(Example<S> example) {
		return this.baseRepository.count(example);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> boolean exists(Example<S> example) {
		return this.baseRepository.exists(example);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Optional<T> findOne(Specification<T> spec) {
		return this.baseRepository.findOne(spec);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll(Specification<T> spec) {
		return this.baseRepository.findAll(spec);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Page<T> findAll(Specification<T> spec, Pageable pageable) {
		return this.baseRepository.findAll(spec, pageable);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll(Specification<T> spec, Sort sort) {
		return this.baseRepository.findAll(spec, sort);
	}
	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public long count(Specification<T> spec) {
		return this.baseRepository.count(spec);
	}
}

定義 UserService

import org.springframework.stereotype.Service;

import io.springboot.jpa.entity.User;

@Service
public class UserService extends AbstractService<User, Integer> {
	
}

添加注解驅動

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories(basePackages = { "io.springboot.jpa.repository" })
@EntityScan(basePackages = { "io.springboot.jpa.entity" })
public class JpaApplication {
	public static void main(String[] args) {
		SpringApplication.run(JpaApplication.class, args);
	}
}

@EnableJpaRepositories指定repository所在的包@EntityScan指定entity所在的包

測試

import io.springboot.jpa.JpaApplication;
import io.springboot.jpa.entity.User;
import io.springboot.jpa.service.UserService;

import java.time.LocalDateTime;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = JpaApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JpaApplicationTest {
	
	static final Logger LOGGER = LoggerFactory.getLogger(JpaApplicationTest.class);
	
	@Autowired
	UserService userService;
	
	@Test
	public void test () {
		// 存儲
		User user = new User();
		user.setAccount("kevinblandy.cn@gmail.com");
		user.setPassword("123456");
		user.setGender(User.Gender.GIRL);
		user.setEnabled(Boolean.TRUE);
		user.setCreatedDate(LocalDateTime.now());
		
		this.userService.save(user);
		
		LOGGER.info("save success.....");
		
		// 檢索
		User results = this.userService.findById(user.getId()).orElseGet(null);
		LOGGER.info("query result={}", results);
	}
}

自動創建的表

CREATE TABLE `user` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
 `account` varchar(50) NOT NULL COMMENT '登錄賬戶',
 `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',
 `enabled` tinyint(1) unsigned NOT NULL COMMENT '是否啟用',
 `gender` tinyint(1) NOT NULL COMMENT '性別。0:男,1:女',
 `last_modified_date` timestamp NULL DEFAULT NULL COMMENT '最后一次修改時間',
 `password` varchar(255) NOT NULL COMMENT '登錄密碼',
 PRIMARY KEY (`id`),
 UNIQUE KEY `UKdnq7r8jcmlft7l8l4j79l1h74` (`account`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用戶';

執行的日志

Hibernate: 
  insert 
  into
    user
    (account, created_date, enabled, gender, last_modified_date, password) 
  values
    (&#63;, &#63;, &#63;, &#63;, &#63;, &#63;)
2020-06-23 17:57:36.264 INFO 7612 --- [      main] i.s.jpa.test.JpaApplicationTest     : save success.....
Hibernate: 
  select
    user0_.id as id1_0_0_,
    user0_.account as account2_0_0_,
    user0_.created_date as created_3_0_0_,
    user0_.enabled as enabled4_0_0_,
    user0_.gender as gender5_0_0_,
    user0_.last_modified_date as last_mod6_0_0_,
    user0_.password as password7_0_0_ 
  from
    user user0_ 
  where
    user0_.id=&#63;
2020-06-23 17:57:36.303 INFO 7612 --- [      main] i.s.jpa.test.JpaApplicationTest     : query result=User [id=1, account=kevinblandy.cn@gmail.com, password=123456, gender=GIRL, createdDate=2020-06-23T17:57:36, lastModifiedDate=null, enabled=true]

以上就是SpringBoot整合spring-data-jpa的方法,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

班玛县| 波密县| 偃师市| 睢宁县| 子洲县| 长寿区| 垫江县| 南部县| 清新县| 崇仁县| 西丰县| 那曲县| 抚州市| 体育| 海南省| 丰城市| 乌苏市| 浮梁县| 彩票| 沙洋县| 高邑县| 垣曲县| 土默特左旗| 芦溪县| 衢州市| 涡阳县| 黔东| 西贡区| 德格县| 茶陵县| 莲花县| 襄垣县| 合作市| 焦作市| 祁门县| 金昌市| 土默特左旗| 山丹县| 长宁区| 浪卡子县| 四子王旗|