需要帮助来创建条件子查询

时间:2016-09-29 12:06:50

标签: java mysql jpa

我是jpa中的初学者,我遇到了复合查询。 然后我开始搜索解决方案。许多人建议使用标准API。

所以问题是:如何使用criteriaQuery创建类似的查询?

MySQL版

SELECT role FROM Role WHERE id_role=(SELECT id_role FROM Client WHERE email=:email)

角色

@Entity
@Table(name="role")
public class Role {

@Id
public int id_role;

private enum  enumRole {ADMIN, CLIENT}

@Column(name="role")
private  enumRole role;

public Role() {
}

public Role(enumRole role) {
    this.role = role;
}

public String getRole() {
    return this.role.name();
}

public void setRole(String role) {
    this.role = enumRole.valueOf(role);
}
@OneToMany(targetEntity = Client.class)
private List clientList;
}

客户端

@Entity
@Table(name ="client")
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public  Long Id;

@Column(name="first_name", length = 25)
private String firstName;

@Column(name="surname", length = 25)
private String surName;

@Column(name="password", length = 30)
private String password;
@Column(name="email")
private String email;

@Column(name="username", length = 15)
private String username;

public Client() {
}

@ManyToMany(targetEntity = Ticket.class)
private Set ticketSet;

public Client(String firstName, String surName, String password, String email, String username) {
    this.firstName = firstName;
    this.surName = surName;
    this.password = password;
    this.email = email;
    this.username = username;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getSurName() {
    return surName;
}

public void setSurName(String surName) {
    this.surName = surName;
}


public String getPassword() {
    return password;
}

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

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

}
}

1 个答案:

答案 0 :(得分:0)

您是否可以在客户端和角色之间创建映射?是@OneToMany还是@ManyToMany?如果是这样,那么你不需要编写任何sql,并且可以使用简单的JPA查询方法http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation