Spring Repository 내에서 원시 SQL을 사용할 수 있습니까?
Spring Data Repository 내에서 원시 SQL을 사용해야합니다. 가능합니까? 내가 보는 모든 것은 @Query
항상 엔티티 기반입니다.
@Query 주석을 사용하면 nativeQuery 플래그를 true로 설정하여 네이티브 쿼리를 실행할 수 있습니다.
SpringData JPA 참조 문서 에서 인용 .
또한 명명 된 네이티브 쿼리로 수행하는 방법에 대한 이 섹션 을 참조하십시오 .
예, 다음 방법으로이 작업을 수행 할 수 있습니다.
1. CrudRepository (투영)
SpringData Repositories는 일반적으로 쿼리 메서드를 사용할 때 도메인 모델을 반환합니다. 그러나 때로는 다양한 이유로 해당 모델의보기를 변경해야 할 수 있습니다.
엔티티가 다음과 같다고 가정합니다.
import javax.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "USER_INFO_TEST")
public class UserInfoTest {
private int id;
private String name;
private String rollNo;
public UserInfoTest() {
}
public UserInfoTest(int id, String name) {
this.id = id;
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", nullable = false, precision = 0)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "name", nullable = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "roll_no", nullable = true)
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
이제 Projection 클래스는 다음과 같습니다. 필요한 필드가 될 수 있습니다.
public interface IUserProjection {
int getId();
String getName();
String getRollNo();
}
그리고 Your Data Access Object(Dao) is like bellow
:
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.ArrayList;
public interface UserInfoTestDao extends CrudRepository<UserInfoTest,Integer> {
@Query(value = "select id,name,roll_no from USER_INFO_TEST where rollNo = ?1", nativeQuery = true)
ArrayList<IUserProjection> findUserUsingRollNo(String rollNo);
}
Now ArrayList<IUserProjection> findUserUsingRollNo(String rollNo)
will give you the list of user.
2. Using EntityManager
Suppose your query is "select id,name from users where roll_no = 1001".
Here query will return a object with id and name column. Your Response class is like bellow:
Your Response class is like:
public class UserObject{
int id;
String name;
String rollNo;
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
here UserObject constructor will get a Object Array and set data with object.
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
Your query executing function is like bellow :
public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {
String queryStr = "select id,name from users where roll_no = ?1";
try {
Query query = entityManager.createNativeQuery(queryStr);
query.setParameter(1, rollNo);
return new UserObject((Object[]) query.getSingleResult());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Here you have to import bellow packages:
import javax.persistence.Query;
import javax.persistence.EntityManager;
Now your main class, you have to call this function. First get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo)
function. Calling procedure is given bellow:
Here is the Imports
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
get EntityManager
from this way:
@PersistenceContext
private EntityManager entityManager;
UserObject userObject = getUserByRoll(entityManager,"1001");
Now you have data in this userObject.
Note:
query.getSingleResult() return a object array. You have to maintain the column position and data type with query column position.
select id,name from users where roll_no = 1001
query return a array and it's [0] --> id and [1] -> name
.
More info visit this thread and this Thread
Thanks :)
It is also possible to use Spring Data JDBC repository, which is a community project built on top of Spring Data Commons to access to databases with raw SQL, without using JPA.
It is less powerful than Spring Data JPA, but if you want lightweight solution for simple projects without using a an ORM like Hibernate, that a solution worth to try.
we can use createNativeQuery("Here Nagitive SQL Query ");
for Example :
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();
It is possible to use raw query within a Spring Repository.
@Query(value = "SELECT A.IS_MUTUAL_AID FROM planex AS A
INNER JOIN planex_rel AS B ON A.PLANEX_ID=B.PLANEX_ID
WHERE B.GOOD_ID = :goodId",nativeQuery = true)
Boolean mutualAidFlag(@Param("goodId")Integer goodId);
'IT story' 카테고리의 다른 글
iOS에서 개인 정보 설정을 재설정 할 수 있습니까? (0) | 2020.09.07 |
---|---|
svn cleanup : sqlite : 데이터베이스 디스크 이미지 형식이 잘못되었습니다. (0) | 2020.09.07 |
AngularJS의 비 싱글 톤 서비스 (0) | 2020.09.07 |
Kotlin에서 추상 클래스의 익명 클래스 인스턴스를 만드는 방법은 무엇입니까? (0) | 2020.09.07 |
Swift에서 'get'과 'set'은 무엇입니까? (0) | 2020.09.07 |