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

溫馨提示×

溫馨提示×

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

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

Spring Data Jpa 復合主鍵的實現

發布時間:2020-09-28 01:12:44 來源:腳本之家 閱讀:233 作者:冬天飲雪水 欄目:編程語言

前言

這次大創有個需求,在數據庫建表時發現,user表與project表的關系表 user_project的主鍵為復合主鍵:

CREATE TABLE user_project(
 user_id      INT(20),
 project_id     INT(20),
 timestamp     VARCHAR (50),
 donate_money    DOUBLE(10,2),
 PRIMARY KEY (user_id,project_id)
);

在網上看了幾篇博客,以及在spring boot干貨群咨詢(感謝夜升額耐心解答)過后總算是做出來了。這里做個總結,方便日后查閱。

正文

這里采用@IdClass注解的方式來實現復合主鍵;

思路

  1. 編寫一個復合主鍵類UserProjectMultiKeysClass;
  2. 通過@IdClass注釋在實體中標注復合主鍵;
  3. 可以通過EntityManager獲取數據,或者是直接在Repository 里寫方法;

實現

復合主鍵類

package com.hzy.Model;

import java.io.Serializable;

/**
 * Created by huangzhenyang on 2017/9/7.
 * UserProject的復合主鍵類
 *
 * @Param userId
 * @Param projectId
 * @Param timestamp
 * 由這三個共同組成復合主鍵
 */
public class UserProjectMultiKeysClass implements Serializable {
  private Integer userId;
  private Integer projectId;
  private String timestamp;

  //Constructor
  public UserProjectMultiKeysClass() {
  }

  public UserProjectMultiKeysClass(Integer userId, Integer projectId, String timestamp) {
    this.userId = userId;
    this.projectId = projectId;
    this.timestamp = timestamp;
  }

  //Setter and Getter
  public Integer getUserId() {
    return userId;
  }

  public void setUserId(Integer userId) {
    this.userId = userId;
  }

  public Integer getProjectId() {
    return projectId;
  }

  public void setProjectId(Integer projectId) {
    this.projectId = projectId;
  }

  public String getTimestamp() {
    return timestamp;
  }

  public void setTimestamp(String timestamp) {
    this.timestamp = timestamp;
  }

  // ***重寫hashCode與equals方法*** 劃重點!
  @Override
  public int hashCode() {
    final int PRIME = 31;
    int result = 1;
    result = PRIME * result + ((userId == null) ? 0 : userId.hashCode());
    result = PRIME * result + ((projectId == null) ? 0 : projectId.hashCode());
    result = PRIME * result + ((timestamp == null) ? 0 : timestamp.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj){
    if(this == obj){
      return true;
    }
    if(obj == null){
      return false;
    }
    if(getClass() != obj.getClass()){
      return false;
    }

    final UserProjectMultiKeysClass other = (UserProjectMultiKeysClass)obj;
    if(userId == null){
      if(other.userId != null){
        return false;
      }
    }else if(!userId.equals(other.userId)){
      return false;
    }
    if(projectId == null){
      if(other.projectId != null){
        return false;
      }
    }else if(!projectId.equals(other.projectId)){
      return false;
    }
    if(timestamp == null){
      if(other.timestamp != null){
        return false;
      }
    }else if(!timestamp.equals(other.timestamp)){
      return false;
    }

    return true;
  }
}

注意:

復合主鍵類必須滿足:
1. 實現Serializable接口;
2. 有默認的public無參數的構造方法;
3. 重寫equals和hashCode方法。equals方法用于判斷兩個對象是否相同,EntityManger通過find方法來查找Entity時,是根據equals的返回值來判斷的。hashCode方法返回當前對象的哈希碼;

實體類

package com.hzy.Model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
import java.io.Serializable;

/**
 * Created by huangzhenyang on 2017/9/7.
 * 
 */
@Entity
@Table(name = "user_project")
@IdClass(UserProjectMultiKeysClass.class)
public class UserProject implements Serializable {
  private double donateMoney;
  private Integer userId;
  private Integer projectId;
  private String timestamp;

  @Id
  public Integer getUserId(){
    return this.userId;
  }

  @Id
  public Integer getProjectId(){
    return this.projectId;
  }

  @Id
  public String getTimestamp(){
    return this.timestamp;
  }

  //getter and setter
  public double getDonateMoney() {
    return donateMoney;
  }

  public void setDonateMoney(double donateMoney) {
    this.donateMoney = donateMoney;
  }

  public void setUserId(Integer userId) {
    this.userId = userId;
  }

  public void setProjectId(Integer projectId) {
    this.projectId = projectId;
  }

  public void setTimestamp(String timestamp) {
    this.timestamp = timestamp;
  }

  @Override
  public String toString() {
    return "UserProject{" +
        "donateMoney=" + donateMoney +
        ", userId=" + userId +
        ", projectId=" + projectId +
        ", timestamp='" + timestamp + '\'' +
        '}';
  }
}

注意:
1. @IdClass標注用于標注實體所使用主鍵規則的類;
2. 在實體中同時標注主鍵的屬性,比如這段代碼中的userId,projectId以及timestamp ;

獲取數據

方法一: 通過EntityManager獲取,比如方法testUserProjectRepository()

方法二:通過Repository獲取;這里記得在extends JpaRepository<UserProject,UserProjectMultiKeysClass>時把id的主鍵類指定為復合主鍵類UserProjectMultiKeysClass

public interface UserProjectRepository extends JpaRepository<UserProject,UserProjectMultiKeysClass>{
  // 根據用戶Id,找出用戶參與的所有UserProject
  // TEST PASS
  List<UserProject> findByUserId(Integer userId);

  // 根據項目id,找出參與項目的所有UserProject
  // TEST PASS
  List<UserProject> findByProjectId(Integer projectId);

  // 根據用戶id和項目id 找出所有的UserProject
  // TEST PASS
  List<UserProject> findByUserIdAndProjectId(Integer userId,Integer projectId);
}

單元測試的代碼

package com.hzy;

import com.hzy.Model.UserProject;
import com.hzy.Model.UserProjectMultiKeysClass;
import com.hzy.Repository.UserProjectRepository;
import com.hzy.Service.UserProjectService;
import com.hzy.Service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by huangzhenyang on 2017/9/8.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserProejctRepositoryTest {
  @Autowired
  @PersistenceContext
  private EntityManager entityManager;

  @Autowired
  private UserProjectRepository userProjectRepository;

  @Test
  public void testUserProjectRepository(){
    UserProjectMultiKeysClass userProjectMultiKeysClass =
        new UserProjectMultiKeysClass(1, 1, "2017-09-08");
    UserProject userProject = entityManager.find(UserProject.class,userProjectMultiKeysClass);
    System.out.println(userProject.toString());
  }


  @Test
  public void testFindByUserId(){
    List<UserProject> userProjects = userProjectRepository.findByUserId(1);
    for(UserProject userProject:userProjects){
      System.out.println(userProject.toString());
    }
  }

  @Test
  public void testFindByProjectId(){
    List<UserProject> userProjects = userProjectRepository.findByProjectId(1);
    for(UserProject userProject:userProjects){
      System.out.println(userProject.toString());
    }
  }

  @Test
  public void testFindByUserIdAndProjectId(){
    List<UserProject> userProjects = userProjectRepository.findByUserIdAndProjectId(1,1);
    for(UserProject userProject:userProjects){
      System.out.println(userProject.toString());
    }
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

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

AI

防城港市| 邳州市| 随州市| 德安县| 潮安县| 巴里| 开封市| 宜都市| 九龙坡区| 洪湖市| 新蔡县| 兴化市| 闻喜县| 南江县| 鱼台县| 永和县| 饶平县| 临夏县| 繁昌县| 新龙县| 北川| 贵溪市| 万州区| 边坝县| 永年县| 巴东县| 利川市| 甘孜县| 宁远县| 文昌市| 华容县| 德昌县| 达日县| 宁南县| 三亚市| 荔浦县| 石首市| 武夷山市| 青州市| 凉山| 甘孜县|