我需要将SQL本机查询结果作为映射,如别名作为键和列值作为Spring启动JPA中的值 例如:
查询SELECT u.first_name as firstName, u.last_name as lastName from user u
返回两行。 JPA中的实体经理应返回
[{
"firstName": "XXX",
"lastName": "YYY"
}, {
"firstName": "AAA",
"lastName": "BBB"
}]
答案 0 :(得分:0)
您可以创建扩展pojo类的存储库,并制定查询方法以提供所需的输出
<强> users.java 强>
@Entity
@Table(name = "USERS")
@EntityListeners(UsersEntityListener.class)
@NamedQueries({
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")})
public class User extends Domain implements Serializable {
private static final long serialVersionUID = 1L;
@Basic(optional = false)
@Column(name = "FIRST_NAME", nullable = false)
private String firstName;
@Basic(optional = false)
@Column(name = "LAST_NAME", nullable = false)
private String lastName;
@Column(name = "MIDDLE_NAME")
private String middleName;
@Basic(optional = false)
@Column(name = "GENDER", nullable = false)
private String gender;
@Basic(optional = false)
@Column(name = "MOBILE", nullable = false)
private String mobile;
@Basic(optional = false)
@Column(name = "EMAIL", nullable = false)
private String email;
@Basic(optional = false)
@Column(name = "USERNAME", nullable = false)
private String username;
@Basic(optional = false)
@Column(name = "PASSWORD", nullable = false)
private String password;
@Column(name = "URL")
private String url;
public User() {
}
//*************Getters and Setters******************/
}
<强> UserRepository.java 强>
@Repository
@RepositoryRestResource
public interface UserRepository extends JpaRepository<User,Integer> {
@Query("select u.firstName,u.lastName from Users u ")
List<BuyingRequirement> find();
}
现在您可以直接使用此方法:
@RestController
@RequestMapping("/api/v1")
public class xyz{
@Autowired
UserRepository ur;
@GetMapping(value = "/user")
public List<Users> getNameandLastName(){
List user= ur.find();
return user;
}
}
这将在键值对中提供所需的结果列表
答案 1 :(得分:0)
您可以尝试以下代码:
import org.hibernate.internal.SessionImpl;
import java.sql.Connection;
Connection connection = entitymanager.unwrap(SessionImpl.class).connection();
PreparedStatement ps = connection.prepareStatement(procedure);`
ResultSet rs = ps.executeQuery();