我是一个实体类User_Details
package vl.cybersecurityapplication.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "User_Details")
public class User_Details implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "UserId")
private int userId;
@Column(name = "FirstName")
private String firstName;
@Column(name = "LastName")
private String lastName;
@Column(name = "Password")
private String password;
@Column(name = "E_Mail")
private String eMail;
@Column(name = "Mobile_Num")
private int mobileNumber;
//getters and setters
}
这是我的repo界面
package vl.cybersecurityapplication.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import vl.cybersecurityapplication.model.User_Details;
public interface IUserRepository extends JpaRepository<User_Details, Long> {
public Integer findMobileNumberByName(String userName);
}
这是我的回购课程
package vl.cybersecurityapplication.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import vl.cybersecurityapplication.model.User_Roles;
@Transactional
@Repository
public class UserRepository{
@Autowired
IUserRepository userRepository;
public Integer findMobileNumberByName(@PathVariable String lastName) {
int mobileNumber = userRepository.findMobileNumberByName("shaik");
System.out.println("Mobile Number : "+mobileNumber);
return mobileNumber;
}
}
我是Spring Boot和JPA的新手。 在这里,我需要使用lastname在User_Details表中查询手机号码。 即,从User_Details中选择Mobile_Num,其中LastName =&#34; xyz&#34 ;; 有人能帮助我如何在我的repo类中编写这个查询。
答案 0 :(得分:1)
无需使用本机查询。 JPA支持基于对象的查询。 您可以使用List findByLastName(String lastname),它将在后端生成该查询并返回结果。
答案 1 :(得分:1)
你可以这样写。但你不能只获取MobileNumber。你会得到一个完整的对象。
List<User> findByLastName(String lastname).
如果您只想获得某些字段,那么您应该查看Projections