波多野结衣 蜜桃视频,国产在线精品露脸ponn,a v麻豆成人,AV在线免费小电影

公告:魔扣目錄網(wǎng)為廣大站長提供免費(fèi)收錄網(wǎng)站服務(wù),提交前請(qǐng)做好本站友鏈:【 網(wǎng)站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(wù)(50元/站),

點(diǎn)擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會(huì)員:747

本文介紹了休眠:無法將數(shù)據(jù)回取到Map<>的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

擁有這些實(shí)體:

User.java

@Entity
@Data
@NoArgsConstructor
public class User {
    @Id @GeneratedValue
    private int id;
    private String username;
    private String about;
    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    private Map<User, Friendship> friendships = new HashMap<>();
    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    private Collection<Post> posts = new ArrayList<>();

    public User(String username) {
        this.username = username;
    }

    public void addFriend(User friend){
        Friendship friendship = new Friendship();
        friendship.setOwner(this);
        friendship.setFriend(friend);
        this.friendships.put(friend, friendship);
    }

    public void addPost(Post post){
        post.setAuthor(this);
        this.posts.add(post);
    }
}

Friendship.java

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Friendship {
    @EmbeddedId
    private FriendshipId key = new FriendshipId();
    private String level;
    @ManyToOne
    @MapsId("ownerId")
    private User owner;
    @ManyToOne
    @MapsId("friendId")
    private User friend;
}

Friendship Id.Java

@Embeddable
public class FriendshipId implements Serializable {
    private int ownerId;
    private int friendId;
}

UserRepository.Java

public interface UserRepository extends JpaRepository<User, Integer> {
    public User findByUsername(String username);
}

和最終DemoApplication.java

@Bean
    public CommandLineRunner dataLoader(UserRepository userRepo, FriendshipRepository friendshipRepo){
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                User f1 = new User("friend1");
                User f2 = new User("friend2");
                User u1 = new User("user1");

                u1.addFriend(f1);
                u1.addFriend(f2);
                userRepo.save(u1);

                User fetchedUser = userRepo.findByUsername("user1");
            System.out.println(fetchedUser);
            System.out.println(fetchedUser.getFriendships().get(f1));

            }
        };
    }

userRepo.save(u1)操作后,各表如下:

mysql> select * from user;
+----+-------+----------+
| id | about | username |
+----+-------+----------+
|  1 | NULL  | user1    |
|  2 | NULL  | friend1  |
|  3 | NULL  | friend2  |
+----+-------+----------+

select * from friendship;
+-------+-----------+----------+-----------------+
| level | friend_id | owner_id | friendships_key |
+-------+-----------+----------+-----------------+
| NULL  |         2 |        1 |               2 |
| NULL  |         3 |        1 |               3 |
+-------+-----------+----------+-----------------+

如您所見,所有朋友都已保存。然而,這一聲明:

        System.out.println(fetchedUser.getFriendships().get(f1));

返回null。即使fetchedUser已獲取朋友圖:

        System.out.println(fetchedUser);

打印:

User(id=1, username=user1, about=null, friendships={User(id=2, username=friend1, about=null, friendships={}, posts=[])=com.example.demo.model.Friendship@152581e8, User(id=3, username=friend2, about=null, friendships={}, posts=[])=com.example.demo.model.Friendship@58a5d38}, posts=[])

那么,當(dāng)Mapfriendships被完全獲取(從上面的語句中可以看到,所有的朋友都被獲取了)時(shí),為什么無法獲取朋友f1(更準(zhǔn)確地說是null)?

PS:

我已經(jīng)刪除了@DataLombok批注(剛剛添加了@Getter@Setter和@NoArgsConstructor`),并親自重寫了equalsAndHashCode:

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;
        User user = (User) o;
        return id == user.id && Objects.equals(username, user.username) && Objects.equals(about, user.about) && Objects.equals(friendships, user.friendships) && Objects.equals(posts, user.posts);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, username, about, friendships, posts);
    }

或者換句話說,equals()方法使用User類的所有字段。

推薦答案

如您所見,所有朋友都已保存。然而,這一聲明:

    System.out.println(fetchedUser.getFriendships().get(f1)); returns null. 

即使fetchedUser擁有好友地圖
已提取:

    System.out.println(fetchedUser);

打?。?/p>

 User(id=1, username=user1, about=null, friendships={User(id=2, username=friend1, about=null, friendships={}, posts=[])=com.example.demo.model.Friendship@152581e8, User(id=3, username=friend2, about=null, friendships={}, posts=[])=com.example.demo.model.Friendship@58a5d38}, posts=[])

問題是,當(dāng)f1User添加到friendshipsHashMap時(shí),主鍵id不存在。它稍后會(huì)在某個(gè)時(shí)候通過Hibernate進(jìn)行更新。這會(huì)更改HashCode值!

hashcode鍵的值在添加到Map后不應(yīng)更改。這就是導(dǎo)致問題的原因。模擬問題的簡單測(cè)試代碼-https://www.jdoodle.com/a/3Bg3

import lombok.*;
import java.util.*;

public class MyClass {
    public static void main(String args[]) {
      Map<User, String> friendships = new HashMap<>();
        User f1 = new User();
        f1.setUsername("friend1");
        
        User f2 = new User();
        f2.setUsername("friend2");
        friendships.put(f1, "I am changed. Can't find me");
        friendships.put(f2, "Nothing changed. So, you found me");
        
        System.out.println(f1.hashCode()); // -600090900
        f1.setId(1); // Some id gets assigned by hibernate. Breaking the hashcode
        System.out.println(f1.hashCode()); // -600090841 (this changed !!!)

        System.out.println(friendships); // prints f1, f2 both
        System.out.println(friendships.get(f1)); // prints null
        System.out.println(friendships.get(f2));
    }
}

// @Data
@Getter
@Setter
@EqualsAndHashCode
@ToString
class User
{
    private int id;
    private String username;
}

解決方案

將用戶添加到映射后,不應(yīng)更改hashcode值。我認(rèn)為有幾個(gè)選擇可以嘗試解決這個(gè)問題-

    在將數(shù)據(jù)庫中的好友放入friendship地圖之前將其持久化。因此該ID已分配。
    根本不要覆蓋equalshashcode。使用默認(rèn)設(shè)置?;趯?duì)象標(biāo)識(shí)。
    使用固定的哈希碼。例如,如果username分配后沒有變化,則該字段可用于生成hashcode值。

這篇關(guān)于休眠:無法將數(shù)據(jù)回取到Map&lt;&gt;的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,

分享到:
標(biāo)簽:amp gt lt Map 休眠 回取到 數(shù)據(jù)
用戶無頭像

網(wǎng)友整理

注冊(cè)時(shí)間:

網(wǎng)站:5 個(gè)   小程序:0 個(gè)  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會(huì)員

趕快注冊(cè)賬號(hào),推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨(dú)大挑戰(zhàn)2018-06-03

數(shù)獨(dú)一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學(xué)四六

運(yùn)動(dòng)步數(shù)有氧達(dá)人2018-06-03

記錄運(yùn)動(dòng)步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績?cè)u(píng)定2018-06-03

通用課目體育訓(xùn)練成績?cè)u(píng)定