我有 2 個表表user有這些欄位
userId
email
Phone
activeFlag
表Comments有這些欄位
userId
Comments
Flag
我想創建這樣的結束查詢
Select * from users a left join Comments b on a.user_id and b.user_id where a.activeFlag='Y' and b.Flag='Y' and a.userId='myuser'
我已經為兩個表創建了映射,其中兩個表都使用 OneToOne 映射進行映射
我已經為它寫了下面的謂詞
public static Specification<User> findUser(String username){
return ((root,criteriaQuery,cb) ->{
List<Predicate> predicates = new ArrayList<Predicate>();
Root<Comments> rootComment = criteriaQuery.from(Comments.class);
predicates.add(cb.equal(root.get("userId"),username));
predicates.add(cb.equal(root.get("activeFlag"),"N"));
criteriaQuery.where(
cb.equal(rootComment.get("Flag"),"N")
);
return cb.and(predicates.toArray(new Predicate[] {}));
}
但它沒有按預期作業。它正在生成下面的查詢,它不包括標志的 where 子句
select comment0_.user_id as user_id1_2_0_, comment0_.active_flag as active_f2_2_0_, comment0_.comments as comments3_2_0_, comment0_.create_date as create_d4_2_0_, comment0_.create_user_id as create_u5_2_0_ from comment comment0_ where comment0_.user_id=?
uj5u.com熱心網友回復:
我會考慮使用 Springs JPARepository,因為它比使用 jpql/criteria 查詢要容易得多。
我從您的描述中假設以下模型:
@Entity
public class User {
@Id
private String userId;
private String email;
private String phone;
private boolean activeFlag;
@OneToOne
private Comment comment;
// Getters Settes
}
@Entity
public class Comment {
@Id
private String userId;
private String email;
private String phone;
private boolean activeFlag;
@OneToOne
private User user;
}
比您可以使用以下存盤庫
@Repository
public interface UserRepository extends JpaRepository<User, String> {
User findByUserIdAndActiveFlagTrue(String userId);
}
并在這樣的地方使用它:
public class SomeClass {
private UserRepository userRepository;
@Autowired
public SomeClass(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findUser(String userName) { // Should be userId, but I match your example
var user = userRepository.findByUserIdAndActiveFlagTrue(userName);
return user;
}
public void useIt(){
var myuser = findUser("myuser");
//access user data
myuser.getEmail();
//access comment
var comment = myuser.getComment();
comment.getComments(); //comments field from your description
}
}
我建議閱讀此 baeldung 教程以更好地理解:https ://www.baeldung.com/the-persistence-layer-with-spring-data-jpa
一般來說:對我來說,您似乎應該重新考慮您的模型設計,因為:
User 和 Comment 之間的 oneToOne 關系似乎很奇怪。一個用途是否始終只能有一個評論?我認為您盡量避免使用 manyToMany,因為 Comments 有一個欄位
comments(復數),您可能在其中存盤多個評論。User 和 Comment 具有相同的命名 Id 列
userId。只需將其命名id為它應該是唯一的,并且不能在用戶和用戶擁有的評論之間共享userId 是字串:通常不會出錯,但不能自動遞增或自動生成。此外,您應該避免使用用戶名作為 id。在互聯網上搜索“自然鍵與代理鍵”。我建議使用
Longas id 甚至更好的 UUID(兩個代理鍵)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/495692.html
