How do i use HibernateTemplate.findByNamedParam()? - java

HI, i am trying to use the above spring hibernate temnplate method do a simple query based on a specific ID from the database but the problem is that the query doesnt replace the ":" character from the sql string below into the value contained in "id".
i thought that this method replaces ":" with the given parameter i set in the method bit it doesnt?
Code is below:
private static final String SQL_GET_FILE = "select new FileObject(filename, size, id, type, file) from FileObject where id = : limit 1";
FileObject file = (FileObject) hbTemplate.findByNamedParam(SQL_GET_FILE, "id", id);
//File object POJO:
package com.kc.models;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import org.hibernate.Hibernate;
public class FileObject {
private String filename;
private String type;
private double size;
private Blob file;
private int id;
public FileObject() {
}
public FileObject(String name, double size, int id, String type) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
}
public FileObject(String name, double size, int id, String type, Blob file) {
this.filename = name;
this.type = type;
this.size = size;
this.id = id;
this.file = file;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFilename() {
return filename;
}
public void setFilename(String fileName) {
this.filename = fileName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public Blob getFile() {
return file;
}
public void setFile(Blob file) {
this.file = file;
}
}
The exception i get is basically this:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: 1 near line 1, column 104 [select new FileObject(filename, size, id, type, file) from com.kc.models.FileObject where id = : limit 1]
org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:31)
org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:24)
org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:59)
org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:258)
org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:157)
org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
org.springframework.orm.hibernate3.HibernateTemplate$31.doInHibernate(HibernateTemplate.java:949)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.findByNamedParam(HibernateTemplate.java:947)
org.springframework.orm.hibernate3.HibernateTemplate.findByNamedParam(HibernateTemplate.java:938)
com.kc.models.DbFileHelper.getFile(DbFileHelper.java:81)
com.kc.models.FileHelper.getFileFromDb(FileHelper.java:195)
com.kc.Controllers.DownloadAppController.handle(DownloadAppController.java:48)
org.springframework.web.servlet.mvc.AbstractCommandController.handleRequestInternal(AbstractCommandController.java:84)
org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Now i have temporarily done a quick fix by simply doing the above
private static final String SQL_GET_FILE = "select new FileObject(filename, size, id, type, file) from FileObject where id = ";
List<FileObject> file = hbTemplate.find(SQL_GET_FILE+id);
But i dont like the idea of joining a query string with +.
it would get tedius if i have a sql looking something like this:
SQL_GET_FILE = "select new FileObject(filename, size, id, type, file)
from FileObject where id = 10 && size < 1000 && type = jpg";
cheers in advance

You should give the parameter a name, not just a colon:
where id = :id
Also, don't use LIMIT - use template.setMaxResults()
Actually, I would advise for using the hibernate Session directly - the HibernateTemplate is something that the guys at Hibernate criticize a lot - see here the comments by Gaving King.
You can still use HibernateTemplate, but for features (like setFirstResult(..)) you can use the Session.
Finally, I think using EntityManager is the best choice. Spring offers very good JPA integration as well.

Related

class java.math.BigInteger cannot be cast to class java.lang.Integer (java.math.BigInteger and java.lang.Integer are in module java.base of load

I am trying to write a handler for a get request in Spring but I am getting this error:
class java.math.BigInteger cannot be cast to class java.lang.String
(java.math.BigInteger and java.lang.String are in module java.base of
loader 'bootstrap').
please check my controller class
#GetMapping("getListOfStudentsBasedOnTrainerId/{trainerId}")
public ResponseEntity<List<TrainerIdResponse>> getListOfStudentsBasedOnTrainerId( #PathVariable int trainerId)
throws RecordNotFoundException{
List<TrainerIdResponse> trainerIdresp= userService.getListOfStudentsBasedOnTrainerId(trainerId);
return new ResponseEntity<List<TrainerIdResponse>>(trainerIdresp,new HttpHeaders(), HttpStatus.OK);
}
this is user service method
public List<TrainerIdResponse> getListOfStudentsBasedOnTrainerId(#PathVariable int trainerId) throws RecordNotFoundException{
List<Object> trainerIdResponse=searchRepository.getListOfStudentsBasedOnTrainerId(trainerId);
Iterator it =trainerIdResponse.iterator();
List<TrainerIdResponse> trainerIdList =new ArrayList<>();
while(it.hasNext()) {
Object[] row=(Object[])it.next();
TrainerIdResponse trainerIdResponse1= new TrainerIdResponse();
trainerIdResponse1.setStudentid(Integer.valueOf((Integer)row[0]).intValue());
trainerIdResponse1.setStudentname(String.valueOf(row[1]));
trainerIdResponse1.setStudentImage(String.valueOf(row[2]));
trainerIdResponse1.setEnrolleddate(String.valueOf(row[3]));
trainerIdResponse1.setHighereducation(String.valueOf(row[4]));
trainerIdResponse1.setUniversity(String.valueOf(row[5]));
trainerIdResponse1.setEmployement(String.valueOf(row[6]));
trainerIdResponse1.setLocation(String.valueOf(row[7]));
trainerIdResponse1.setTrainerid(Integer.valueOf((Integer)row[8]).intValue());
trainerIdList.add(trainerIdResponse1);
}
return trainerIdList;
}
my search repository class
#Query(value ="select u.userid as \"studentid\",u.username as \"studentname\",u.Image_url as \"studentImage\",u.addeddate as \"enrolleddate\", u.highestqualification as \"highereducation\",\r\n"
+ "u.college as \"university\",e.employmenttype as \"employement\",e.location,\r\n"
+ "ur.requestedtoid as \"trainerid\" from users u JOIN userexperience e \r\n"
+ "on u.userid = e.userid join userrequests ur on u.userid = ur.requestedtoid \r\n"
+ "where u.userid = ur.requestedtoid or u.userid =:trainerId",nativeQuery = true)
List<Object> getListOfStudentsBasedOnTrainerId(int trainerId);
my response class
import java.util.Date;
public class TrainerIdResponse {
private int studentid;
private String studentname;
private String studentImage;
private String enrolleddate;
private String highereducation;
private String university;
private String employement;
private String location;
private int trainerid;
public int getStudentid() {
return studentid;
}
public void setStudentid(int studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getStudentImage() {
return studentImage;
}
public void setStudentImage(String studentImage) {
this.studentImage = studentImage;
}
public String getEnrolleddate() {
return enrolleddate;
}
public void setEnrolleddate(String enrolleddate) {
this.enrolleddate = enrolleddate;
}
public String getHighereducation() {
return highereducation;
}
public void setHighereducation(String highereducation) {
this.highereducation = highereducation;
}
public String getUniversity() {
return university;
}
public void setUniversity(String university) {
this.university = university;
}
public String getEmployement() {
return employement;
}
public void setEmployement(String employement) {
this.employement = employement;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getTrainerid() {
return trainerid;
}
public void setTrainerid(int trainerid) {
this.trainerid = trainerid;
}
}
There's a lot of "noise" in the comments, hence this "response":
Q: What is the actual error message?
Your title:
class java.math.BigInteger cannot be cast to class java.lang.Integer
(java.math.BigInteger and java.lang.Integer are in module java.base of
load
Your body:
class java.math.BigInteger cannot be cast to class java.lang.String
(java.math.BigInteger and java.lang.String are in module java.base of
loader 'bootstrap').
??Which is it????
Q: What line of is causing the error?
That's an important reason you're being asked for the stack traceback: the traceback will show where in the source code the error is occurring.
POSSIBLE GUESSES:
trainerIdResponse1.setStudentid(Integer.valueOf((Integer)row[0]).intValue());
trainerIdResponse1.setTrainerid(Integer.valueOf((Integer)row[8]).intValue());
Q: If the guess is correct, what are the data types of row[0] and row[8] in the underlying database? Do they correspond to Java "BigInteger"?
You CANNOT cast "BigInteger" to an Integer. It's possible that's your entire problem. You MAY use BigInteger.intValue().
EXAMPLE:
int myInt = myBigInteger.intValue();
Finally, if the underlying value in the database indeed corresponds to a Java BigInteger, you CANNOT use "intValue()" to read it. You'll probably need getBigDecimal().
Please let us know if any of this information helped.
And please "edit" your post with all the requested information.
Per the OP
private int studentid; inside database this is bigserial data type and
trainerid this is inside db is int8
So this is the necessary code:
BigInteger studentId = row[0].getBigDecimal();
trainerIdResponse1.setStudentid(studentId.intValue());
Long trainerId = row[8].getLong();
trainerIdResponse1.setTrainerid(trainerId.intValue()).
NOTE: both are narrowing conversions - you risk truncating data.

Dropwizard JDBI 3 ResultSetMapper ignore field

I have this Pojo:
private long id;
#NotEmpty
#JsonProperty("name")
private String name;
#NotEmpty
#JsonProperty("id")
private String tagUuid;
#NotEmpty
#JsonProperty("archived")
private boolean archived;
#NotEmpty
#JsonProperty("creationDate")
private DateTime creationDate;
private Integer count;
#JsonCreator
public Tag() {
}
public Tag(long id, String tagUuid, String name, boolean archived, Timestamp creationDate, Integer count) {
this.id = id;
this.tagUuid = tagUuid;
this.name = name;
this.archived = archived;
this.creationDate = new DateTime(creationDate);
this.count = count;
}
This is my result set mapper:
public class TagMapper implements ResultSetMapper<Tag> {
#Override
public Tag map(int index, ResultSet r, StatementContext ctx) throws SQLException {
return new Tag(
r.getLong("id"),
r.getString("tag_uuid"),
r.getString("name"),
r.getBoolean("archived"),
r.getTimestamp("creation_date"),
r.getInt("count")
);
}
}
How can I fetch from the database one column less. For example in some queries I fetch only tagUuid and name and not the other fields.
But if I do this I get this exception: org.skife.jdbi.v2.exceptions.ResultSetException: Exception thrown while attempting to traverse the result set. I tried to create a addtional Tag Constructor without the other parameters.
This is the query I try to run:
#SqlQuery("SELECT t.id, t.tag_uuid as tag_uuid, t.name, t.archived, t.creation_date FROM tags t WHERE t.tag_uuid = :tag_uuid LIMIT 1")
public Tag fetchTagByUuid(#Bind("tag_uuid") String tagUuid);
You can just return the extra column in your query SQL.
#SqlQuery("SELECT t.id, t.tag_uuid as tag_uuid, t.name, t.archived, " +
"t.creation_date, 0 AS count FROM tags t " +
"WHERE t.tag_uuid = :tag_uuid LIMIT 1")
public Tag fetchTagByUuid(#Bind("tag_uuid") String tagUuid);
You can retrieve the values whatever you want and before passing the values to Tag constructor check their existence in the ResultSet. If the attribute is not present then you can pass the default value for the attributes.
You can check the value as r.getString("tag_uuid") != null (for strings)
then tag_uuid = r.getString("tag_uuid")

Java JPA error; You have attempted to set a value of type class data expected type of int from query string

I have error of java JPA project below. Could anyone help me? Thank you.
Type Exception Report
Message You have attempted to set a value of type class data.CityMake for parameter cityMakeMakeID with expected type of int from query string Select f from Foodmodel f WHERE f.cityMakeMakeID = :cityMakeMakeID order by f.foodModelName.
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.IllegalArgumentException: You have attempted to set a value of type class data.CityMake for parameter cityMakeMakeID with expected type of int from query string Select f from Foodmodel f WHERE f.cityMakeMakeID = :cityMakeMakeID order by f.foodModelName.
org.eclipse.persistence.internal.jpa.QueryImpl.setParameterInternal(QueryImpl.java:933)
org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:593)
dao.FoodModelDAO.getModels(FoodModelDAO.java:69)
servlets.StartServlet.processRequest(StartServlet.java:67)
servlets.StartServlet.doGet(StartServlet.java:86)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
--------------------------------FoodModelDAO.java---------------------
public class FoodModelDAO
{
public static List<Foodmodel> getModels(int makeid)
{
CityMake make = CityMakeDAO.findMakeById(makeid);
EntityManager em = DBUtil.getEmFactory().createEntityManager();
String qString = "Select f from Foodmodel f " +
"WHERE f.cityMakeMakeID = :cityMakeMakeID " +
"order by f.foodModelName";
TypedQuery<Foodmodel> query = em.createQuery(qString, Foodmodel.class);
query.setParameter("cityMakeMakeID", make );
try
{
List<Foodmodel> models = query.getResultList();
return models;
}
catch(NoResultException e)
{
return new ArrayList<Foodmodel>();
}
finally
{
em.close();
}
}
}
---------------FoodModel.java post 4/2/2018-----------------------
I have updated FoodModel post again.
enter code here
#Entity
public class FoodModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long foodModelId;
private String foodModelName;
#OneToOne
private CityMake cityMakeMakeID;
public FoodModel() {
foodModelName = "";
}
public FoodModel(Long m, String v, CityMake makeObj) {
foodModelId = m;
foodModelName = v;
//citymake = makeObj;
cityMakeMakeID = makeObj;
}
public Long getModelId() {
return foodModelId;
}
public void setModelId(Long id) {
foodModelId = id;
}
public String getModelName() {
return foodModelName;
}
public void setModelName(String value) {
this.foodModelName = value;
}
public CityMake getMake() {
//return citymake;
return cityMakeMakeID;
}
public void setMake(CityMake make) {
//this.citymake = make;
this.cityMakeMakeID = make;
}
}
query.setParameter("cityMakeMakeID", makeid);
Why? You are creating a typed query for Foodmodel.class, so the parameter types should correspond with the model (looking at FoodModel, the attribute is defined as int).
#Column(name = "CityMake_MakeID")
private int cityMakeMakeID;
If your model was defined like this, the way you are doing it should work:
#OneToOne //Or any type of relation that matches your needs
private CityMake cityMakeMakeID; //See the variable Type

how to upload file and save file in db use spring boot and jpa?

I am new in spring boot.I wanna upload a small file use spring boot and save it in db use jpa.
But I don't have good resolution.
My program like these:
database table:
CREATE TABLE `report` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`logo` BLOB NOT NULL,
`created_time` int(10) NOT NULL,
`updated_time` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8
jpa bean:
Report.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name="mf_report")
public class Report implements Serializable{
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Lob
#Column(name="logo", length=100000)
private byte[] logo;
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 byte[] getLogo() {
return logo;
}
public void setLogo(byte[] logo) {
this.logo = logo;
}
}
ReportReposity.java:
#Repository
public interface ReportRepository extends CrudRepository<Report,Long>{
}
ReportService.java:
#Service
public class ReportService extends CrudService<Report, ReportRepository> {
private final static Logger logger = LoggerFactory.getLogger(ReportService.class);
#Override
#Autowired
public void setRepo(ReportRepository repo) {
this.repo = repo;
}
#Override
public Report copy(Report from, Report to) {
to = from;
return to;
}
#Autowired
private ReportRepository reportRepository;
public boolean saveReportByRequestBean(ReportAddQueryRequest reportBeanQueryRequest){
try {
Report report = new Report();
report.setName(reportBeanQueryRequest.getName());
report.setLogo(reportBeanQueryRequest.getLogo());
long now = System.currentTimeMillis()/1000;
report.setCreateTime(now);
report.setUpdateTime(now);
this.save(report);
}catch (Exception e){
logger.error("save report error:", e);
return false;
}
return true;
}
}
ReportParamBean.java:
import org.hibernate.validator.constraints.NotEmpty;
import java.io.Serializable;
public class ReportParamBean extends AbsRequest implements Serializable {
private long reportId;
#NotEmpty(message = "Param 'name' can't be NULL")
private String name;
private String logo;// In fact, I don't know what type should logo be, File or ?
}
AbsRequest.java:
public class AbsRequest implements Serializable {
private static final long serialVersionUID = -8928786145900600868L;
#NotEmpty(message = "Param 'token' can't be NULL")
#NotNull
private String token;
#NotEmpty(message = "Param 'sign' can't be NULL")
private String sign;
#Min(value = 1, message = "Param 'time' is invalid")
private Long time;
#Min(value = -1, message = "Param 'nodeId' is invalid")
#NotNull(message = "Param 'nodeId' can't be NULL")
private Long nodeId;
private String nodeName;
#Override
public String toString() {
return new ToStringBuilder(this)
.append("token", token)
.append("sign", sign)
.append("time", time)
.append("nodeId", nodeId)
.append("nodeName", nodeName)
.toString();
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
}
ReportController.java:
#RestController
#RequestMapping("/api")
public class ReportController {
#Autowired
private ReportService reportService;
#RequestMapping(value = "/report", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public JSONObject createReport(#RequestBody ReportAddQueryRequest reportBeanQueryRequest){
boolean result = reportService.saveReportByRequestBean(reportBeanQueryRequest);
if (!result){
return ResponseWrapper.buildResponse(RTCodeEnum.C_SERVICE_NOT_AVAILABLE, "add report failed");
}
return ResponseWrapper.buildResponse(RTCodeEnum.C_OK, "add report success");
}
}
I don't know whether I can post a file and other params to server in just one post request,then save the data in db.Could you give me resolution.
Special thanks.
Use Spring's multipart file. In simple implementation you can then get InputStream from it, read the content of the file (being saved on hdd) to a byte array and save it to database.
Consider up voting if this answer help you.
suppose you want to upload a file's data to database then you could do it in two steps:
upload your file as multipart file in your controller class.
#PostMapping("/uploadYourFile")
public String uploadFile( MultipartFile file) throws IOException {
FileInputStream inputStream = (FileInputStream) file.getInputStream();
//you can use inputStream object which currently has your "file" data
// you can process this to fetch your data.
return "file uploaded successfully ";
}
Read your uploaded file"inputStream" fetch the data and insert it into your DB through your db query
I have made an app to upload, download and delete files to/from database using Spring Boot Rest APIs. I also used Spring Web MultipartFile interface to handle HTTP multi-part requests.
Source code: https://github.com/OusamaELIDRISSI/upload-files-database
Happy coding 🙂

Is it possible to use raw SQL within a Spring Repository

I need to use raw SQL within a Spring Data Repository, is this possible? Everything I see around #Query is always entity based.
The #Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
YES, You can do this in bellow ways:
1. By CrudRepository (Projection)
Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons.
Suppose your entity is like this :
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;
}
}
Now your Projection class is like below. It can those fields that you needed.
public interface IUserProjection {
int getId();
String getName();
String getRollNo();
}
And 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 an object with id and name column. Your Response class is like bellow:
Your Response class is like this:
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 an Object Array and set data with the 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. The calling procedure is given below:
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 the 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 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);
we can use createNativeQuery("Here Native SQL Query ");
for Example :
Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();
This is how you can use in simple form
#RestController
public class PlaceAPIController {
#Autowired
private EntityManager entityManager;
#RequestMapping(value = "/api/places", method = RequestMethod.GET)
public List<Place> getPlaces() {
List<Place> results = entityManager.createNativeQuery("SELECT * FROM places p limit 10").getResultList();
return results;
}
}
It is also possible to use Spring Data JDBC, which is a fully supported Spring 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.

Categories

Resources