Hibernate: Cannot fetch data back to Maplt;gt;(休眠:无法将数据回取到Maplt;gt;)
问题描述
拥有这些实体:
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=[])
那么,当Mapfriendships
被完全获取(从上面的语句中可以看到,所有的朋友都被获取了)时,为什么无法获取朋友f1
(更准确地说是null
)?
PS:
我已经删除了@Data
Lombok批注(刚刚添加了@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
类的所有字段。
推荐答案
问题是,当如您所见,所有朋友都已保存。然而,这一声明:
即使fetchedUser拥有好友地图 已提取:System.out.println(fetchedUser.getFriendships().get(f1)); returns null.
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=[])
f1
User
添加到friendships
HashMap时,主键id
不存在。它稍后会在某个时候通过Hibernate进行更新。这会更改HashCode值!
hashcode
键的值在添加到Map
后不应更改。这就是导致问题的原因。模拟问题的简单测试代码-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;
}
解决方案
将用户添加到映射后,不应更改hashcode
值。我认为有几个选择可以尝试解决这个问题-- 在将数据库中的好友放入
friendship
地图之前将其持久化。因此该ID已分配。 - 根本不要覆盖
equals
和hashcode
。使用默认设置。基于对象标识。 - 使用固定的哈希码。例如,如果
username
分配后没有变化,则该字段可用于生成hashcode
值。
这篇关于休眠:无法将数据回取到Map<;>;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:休眠:无法将数据回取到Map<;>;
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01