How to POST ArrayList to spring boot H2 DB - java

Im getting the following error:
{"timestamp":1535929757444,"status":500,"error":"Internal Server Error","exception":"org.springframework.dao.DataIntegrityViolationException","message":"could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.WT_TASK(TASK_ID)\"; SQL statement:\ninsert into wt_task (exercise_id, task_id) values (?, ?) [23505-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement","path":"/api/word-transformation/new"}
I was able to create a service to fetch JSON from the database but I cant manage to upload them.
This is my service:
public WordTransformationExercise save(WordTransformationExerciseRequest wtRequest) {
WordTransformationExercise wordTransformation = new WordTransformationExercise();
wordTransformation.setAuthorId(wtRequest.getAuthor_id());
List<WordTransformationTaskRequest> testP = wtRequest.getwt_task();
List<WordTransformation> thisIsIt = new ArrayList<WordTransformation>();
for(WordTransformationTaskRequest task : testP) {
WordTransformation send = new WordTransformation();
send.setBody(task.getBody());
send.setResult(task.getResult());
send.setWord(task.getWord());
send.setWordAtIndex(task.getWord_at_index());
thisIsIt.add(send);
}
wordTransformation.setwt_task(thisIsIt);
this.wtRepository.save(wordTransformation);
return wordTransformation;
}
This is my Entity:
#Entity
#Table(name = "wt_exercise")
public class WordTransformationExercise implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "author_id")
private Long authorId;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "wt_task",
joinColumns = #JoinColumn(name = "exercise_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "task_id", referencedColumnName = "task_id"))
private List<WordTransformation> wt_task;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAuthorId() {
return authorId;
}
public void setAuthorId(Long authorId) {
this.authorId = authorId;
}
public void setwt_task(List<WordTransformation> list) {
this.wt_task = list;
}
public Collection<?> getwt_task() {
return this.wt_task;
}
}
This is Task entity:
#Entity
#Table(name = "wt_task")
public class WordTransformation implements Serializable {
#Id
#Column(name = "task_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long task_id;
#Column(name = "body")
private String body;
#Column(name = "result")
private String result;
#Column(name = "word")
private String word;
#Column(name = "word_at_index")
private Integer wordAtIndex;
#Column(name = "exercise_id")
private Long exercise_id;
public void setExercise_id(Long exercise_id) {
this.exercise_id = exercise_id;
}
public Long getExercise_id() {
return exercise_id;
}
public void setId(Long task_id) {
this.task_id = task_id;
}
public Long getId() {
return task_id;
}
public void setBody(String body) {
this.body = body;
}
public String getBody() {
return body;
}
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
public void setWord(String word) {
this.word = word;
}
public String getWord() {
return word;
}
public void setWordAtIndex(Integer wordAtIndex) {
this.wordAtIndex = wordAtIndex;
}
public Integer getWordAtIndex() {
return wordAtIndex;
}
}
My API is returning 'id' and 'authorId' fine when I set wt_task to null
This is an example of my sql:
INSERT INTO wt_exercise (id, author_id) VALUES (2, 2);
INSERT INTO wt_task (body, result, word, word_at_index, exercise_id, task_id) VALUES ('please start ', 'running', 'run', 13, 2, 2);

It depends on what you are trying to do.
If you are trying to update an existing entity, you should retrieve it from your repository and set the values instead of creating a new object and trying to save it with an existing key.
If you are trying to create something new then don't set the key at all.

Related

LEFT JOIN table mapping in hibernate

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.websystique.springmvc.model.AssetMakeMaster#0]
I have two entities are as follows:
1. AssetMaster
2. AssetMakeMaster
Above entities are mapped with tables. I want to use left join for above two entities and get the all the data from AssetMaster. Inner query is working fine for above entities but i want get the non matched values also. I have tried but not getting solution yet. Please anyone will give the solution for my problem.
I have tried the below query in mysql it gives me proper result but i want to get result from hibernate entities. Please give me solution for below query:
SELECT * FROM fscassets.asset_master a left join
fscassets.asset_make_master b on a.make=b.id;
/* * To change this license header, choose License Headers in Project
Properties. * To change this template file, choose Tools | Templates
* and open the template in the editor. */ package > >
/** * * #author Amol */
#Entity #Table(name = "asset_master")
public class AssetMaster implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "make", nullable = false)
private int make;
#Column(name = "serialno", nullable = false)
private String serialno;
#Column(name = "specs", nullable = false)
private String specs;
#Column(name = "model", nullable = false)
private String model;
#Column(name = "quantity", nullable = false)
private int quantity;
#Column(name = "purchasedate", nullable = false)
private String purchasedate;
#Column(name = "created_on", nullable = false)
private String createdOnDate;
#Column(name = "remark", nullable = false)
private String remark;
#Column(name = "ipaddress", nullable = false)
private String ipAddress;
#ManyToOne(cascade = CascadeType.ALL)
#Fetch(FetchMode.SELECT)
#JoinColumn(name = "make", updatable = false, insertable = false)
private AssetMakeMaster assetMakeMasterdata;
public AssetMakeMaster getAssetMakeMasterdata() {
return assetMakeMasterdata;
}
public void setAssetMakeMasterdata(AssetMakeMaster assetMakeMasterdata) {
this.assetMakeMasterdata = assetMakeMasterdata;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedOnDate() {
return createdOnDate;
}
public void setCreatedOnDate(String createdOnDate) {
this.createdOnDate = createdOnDate;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public int getMake() {
return make;
}
public void setMake(int make) {
this.make = make;
}
public String getSerialno() {
return serialno;
}
public void setSerialno(String serialno) {
this.serialno = serialno;
}
public String getSpecs() {
return specs;
}
public void setSpecs(String specs) {
this.specs = specs;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getPurchasedate() {
return purchasedate;
}
public void setPurchasedate(String purchasedate) {
this.purchasedate = purchasedate;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
/* * To change this license header, choose License Headers in Project
Properties. * To change this template file, choose Tools | Templates
* and open the template in the editor. */ package > >
/** * * #author Amol */
#Entity
#Table(name = "asset_make_master")
public class AssetMakeMaster implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty
#Column(name = "asset_make_name", unique = true, nullable = false)
private String assetmakename;
#Column(name = "assetgroup", nullable = false)
private int groupid;
#Column(name = "created_on", nullable = false)
private String createdOnDate;
#Column(name = "ipaddress", nullable = false)
private String ipAddress;
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "assetMakeMasterdata")
private List<AssetMaster> assetMakeMasters = new ArrayList<AssetMaster>();
public List<AssetMaster> getAssetMakeMasters() {
return assetMakeMasters;
}
public void setAssetMakeMasters(List<AssetMaster> assetMakeMasters) {
this.assetMakeMasters = assetMakeMasters;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAssetmakename() {
return assetmakename;
}
public void setAssetmakename(String assetmakename) {
this.assetmakename = assetmakename;
}
public int getGroupid() {
return groupid;
}
public void setGroupid(int groupid) {
this.groupid = groupid;
}
public String getCreatedOnDate() {
return createdOnDate;
}
public void setCreatedOnDate(String createdOnDate) {
this.createdOnDate = createdOnDate;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
}
You can't use (*) in HQL query. If you want non matched values also then select that columns individually you will get values.
the problem is a that you are fetching a AssetMaster that has the AssetMakeMaster id setted, but the AssetMakeMaster with the setted id is not in database anymore.

Thread hangs on calling getResultList()

I have a strange problem with JPA. In my sheduler executing next code
#SuppressWarnings("unchecked")
#Transactional
public void refreshSmsStatuses() {
try {
log.info("Enter refreshSmsStatuses");
EntityManager em = hibernateHelper.getEntityManager();
log.info("EM created");
List<Sms> lSms = null;
log.info("lSms = null;");
TypedQuery<Sms> smsQuery = em.createQuery(
"SELECT sms FROM Sms AS sms
join sms.status as status
WHERE status.isFinal = 0
and sms.remoteId is not null
and sms.sendDate > sysdate - 3", Sms.class);
log.info("sqlQuery created");
lSms = smsQuery.getResultList();
log.info("Query SMS executed");
.....
After planning nighty reboot it works several times and hangs. There are next strings
2018-12-17 00:10:33,802 [SmsDao.java:pool-2-thread-1:166] - lSms = null;
2018-12-17 00:10:33,802 [SmsDao.java:pool-2-thread-1:168] - sqlQuery created
in log files. The query does not execute in DB, it hangs somewhere in JPA. Problem is on only production server. After hanging any sheduler's methods don't work, because, I think they wait for the end of this method.
If anybody run into with similar problem, please help me.
Thanks a lot
UPDATED
#Table( name = "ZUSB_SMS")
#Entity
public class Sms extends BaseModel {
private static final long serialVersionUID = -3624326750555670797L;
#Id
#SequenceGenerator(name = "generator", sequenceName = "ZUSB_SMS_SEQ")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "generator")
#Column(name = "id")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_SMS_TEMPLATE_ID", referencedColumnName = "id")
private SmsTemplate template;
#Column(name = "name")
private String name;
#Column(name = "send_date")
private Date sendDate;
#Column(name = "phone")
private String phone;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_CLIENT_ID", referencedColumnName = "id")
private Client client;
#Column(name = "text")
private String text;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_SMS_STATUS_ID", referencedColumnName = "id")
private SmsStatus status;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_USER_ID", referencedColumnName = "id")
private User user;
#Column(name = "remote_id")
private Long remoteId;
private String log = "";
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_CLE_STATUS_ID", referencedColumnName = "id")
private SmsCleStatus cleStatus;
#Column(name = "cle_text")
private String cleText;
#Column(name = "cle_id")
private Long cleId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public SmsTemplate getTemplate() {
return template;
}
public void setTemplate(SmsTemplate template) {
this.template = template;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public SmsStatus getStatus() {
return status;
}
public void setStatus(SmsStatus status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getRemoteId() {
return remoteId;
}
public void setRemoteId(Long remoteId) {
this.remoteId = remoteId;
}
public String getLog() {
return log;
}
public void setLog(String log) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
if(log.equals(""))
this.log = reportDate + " " + log;
else
this.log = this.log + "\n" + reportDate + " " + log;
}
public SmsCleStatus getCleStatus() {
return cleStatus;
}
public void setCleStatus(SmsCleStatus cleStatus) {
this.cleStatus = cleStatus;
}
public String getCleText() {
return cleText;
}
public void setCleText(String cleText) {
this.cleText = cleText;
}
public Long getCleId() {
return cleId;
}
public void setCleId(Long cleId) {
this.cleId = cleId;
}
}
P.S. Sorry for my English
First, your query is not correct since you didn't specify ON what you are joining. Second, You don't need to join SmsStatus table explicitly since you mapped it with #ManyToOne.
Update your query like this-
TypedQuery<Sms> smsQuery = em.createQuery(
"FROM Sms s
WHERE s.status.isFinal = 0
AND s.remoteId IS NOT NULL
AND s.sendDate > sysdate-3", Sms.class);
This may solve the problem.

ModelMapper fail to convert java.util.list to java.util.list on DeleteMapping

good day everyone,
i have this project where i use the ModelMapper to mat my entities to DTOs and vise-versa, and also have a class with #ElementCollection relation.
the mapper seems to work fine for all other methods and it just output the entity as i want, however when it comes to delete mapping i get the following error printed along with a 500 http status. here's the error:
"ModelMapper mapping errors:\r\n\r\n1) Converter org.modelmapper.internal.converter.CollectionConverter#ddb7bc7 failed to convert java.util.List to java.util.List.\r\n\r\n1 error"
here is code:
the entity class:
#Entity
#Table(name = "quiz_engines")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(
value = {"lastModified"},
allowGetters = true
)
public class Engine implements Model {
#Id
#Column(name = "engine_id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY,optional = false, targetEntity = com.QCMGenerator.QCMGenerator.Model.Test.class)
#JoinColumn(name = "test_id", referencedColumnName = "test_id", nullable = false, updatable = false)
#OnDelete(action = OnDeleteAction.NO_ACTION)
#JsonIgnore
private Test test;
#Column(name = "quiz_name", nullable = false)
#NotNull
private String name;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "last_modified", nullable = false)
#LastModifiedDate
private Date lastModified;
#ElementCollection
#CollectionTable(name = "engine_constraints", joinColumns = #JoinColumn(name = "engine_id"))
private List<EngineConstraint> constraints;
public Engine() {
}
public Engine(#NotNull String name, List<EngineConstraint> constraints) {
this.name = name;
this.constraints = constraints;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the DTO class:
public class EngineDTO implements ModelDTO {
private Long id;
#JsonIgnore
private TestDTO test;
private String name;
private Date lastModified;
private List<EngineConstraint> constraints;
public EngineDTO() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TestDTO getTest() {
return test;
}
public void setTest(TestDTO test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the Delete Controller:
#DeleteMapping("/{engineID}")
public ResponseEntity<NonPaginatedResponse> deleteEngine(
#PathVariable(value = "testID") Long testID,
#PathVariable(value = "engineID") Long engineID
){
if(!testRepo.existsById(testID)){
throw new ResourceNotFoundException("No test with the ID '"+testID+"' was found...");
}
return engineRepo.findById(engineID).map(engineFound -> {
engineRepo.delete(engineFound);
return ResponseEntity.status(HttpStatus.OK).body(
ResponseBodyBuilder.getSingleResponse(
convertToDTO(engineFound),
new ModelDTO[]{ convertToDTO(testRepo.findById(testID).get()) },
"delete"
)
);
}
).orElseThrow(
() -> new ResourceNotFoundException("No Engine with the ID '"+engineID+"' was found...")
);
}
hope you guys can help with this one, thank for your time everyone and have a good day.

Hibernate Filters not working

I have two entities mapped with OneToOne that are defined as follow:
Category
#Entity
#Table(name = "category")
#FilterDef(name = "currentLang", parameters = {
#ParamDef(name = "lang", type = "string")
})
public class Category implements Serializable {
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "dt")
private String dt;
#Column(name = "enable", length = 5)
private String enable;
#OneToOne()
#Filter(name = "currentLang", condition = ":lang = lang")
#JoinColumn(name = "context_id", nullable = false, updatable = false, referencedColumnName = "link")
private Context context;
public int getId() {
return id;//test
}
public void setId(int id) {
this.id = id;
}
public String getDt() {
return dt;
}
public void setDt(String dt) {
this.dt = dt;
}
public String getEnable() {
return enable;
}
public void setEnable(String enable) {
this.enable = enable;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public Category() {
}
public Category(String dt, String enable) {
this.dt = dt;
this.enable = enable;
}
}
Context
#Entity
#Table(name = "context")
#Component
#Scope("session")
public class Context implements Serializable {
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "text")
private String text;
#Column(name = "lang")
private String lang;
#Column(name = "link")
private Integer link;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public Context(String text, String lang) {
this.text = text;
this.lang = lang;
}
public Context() {
}
public Integer getLink() {
return link;
}
public void setLink(Integer link) {
this.link = link;
}
}
The following snippet retrieves the model category.
List<com.blog.blog.entity.Category> categories = categoryService.getAll();
com.blog.blog.entity.Category category = categories.get(0);
org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
logger.info(category.getEnable());
logger.info(category.getContext().getText());
But the filter is not working, the result is wrong and a wrong query is recorded in log.
Info: Hibernate: select category0_.id as id1_0_, category0_.context_id as context_4_0_, category0_.dt as dt2_0_, category0_.enable as enable3_0_ from category category0_
Info: Hibernate: select context0_.id as id1_1_0_, context0_.lang as lang2_1_0_, context0_.link as link3_1_0_, context0_.text as text4_1_0_ from context context0_ where context0_.link=?
You need to enable filter and set parameters if needed
Session session = sessionFactory.getCurrentSession();
Filter filter = session.enableFilter("currentLang");
filter.setParameter("lang", getLang());

JPA CriteriaBuilder Subquery multiselect

I have a question about Subquery class in jpa.
I need to create subquery with two custom field, but subquery doesn't have multiselect method and select method has Expression input parameter(In query this is Selection) and constact method not suitable.
Also I have question about join subquery results, It is possible? And how to?
I have:
Chain Enitity
public class Chain {
#Id
#Column(name = "chain_id")
#GeneratedValue(generator = "seq_cha_id", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "seq_cha_id", sequenceName = "SEQ_CHA_ID", allocationSize = 1)
private Long id;
#Column(name = "user_id")
private Long userId;
#Column(name = "operator_id")
private Long operatorId;
#Column(name = "subject")
private String subject;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "chain")
private List<Message> messages;
#Column(name = "status")
private Status status;
public Long getOperatorId() {
return operatorId;
}
public void setOperatorId(Long operatorId) {
this.operatorId = operatorId;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String theme) {
this.subject = theme;
}
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
}
Message Enitity
public class Message {
#Id
#Column(name = "message_id")
#GeneratedValue(generator = "seq_mess_id", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "seq_mess_id", sequenceName = "SEQ_MESS_ID", allocationSize = 1)
private Long id;
#Column(name = "user_id")
private Long userId;
#Column(name = "message", nullable = true, length = 4000)
private String message;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "chain_id")
private Chain chain;
#Column(name = "creation_date")
private Date date;
#Column(name = "status")
private Status status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Chain getChain() {
return chain;
}
public void setChain(Chain chain) {
this.chain = chain;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
Wrapper for query
public class MessageWrapper {
private final Long chainId;
private final Long messageId;
public MessageWrapper(Long chainId, Long messageId) {
this.chainId = chainId;
this.messageId = messageId;
}
}
I need to create this query (this is part of query, another part I get from predicates. JPQL not suitable)
SELECT ch.*
FROM hl_chain ch,
(SELECT mes.chain_id,
max(message_id) message_id
FROM hl_message mes
GROUP BY chain_id) mes
WHERE mes.chain_id = ch.chain_id
ORDER BY message_id;
In Subquery I do
Subquery<MessageWrapper> subquery = criteriaQuery.subquery(MessageWrapper.class);
Root<Message> subRoot = subquery.from(Message.class);
subquery.select(cb.construct(
MessageWrapper.class,
subRoot.get(Message_.chain),
cb.max(subRoot.get(Message_.id))
));
But, the subquery doesn't have select with CompoundSelection in params and I can't use the CriteriaBuilder construct method.
A view on database mapped as an entity will do the job you need.
It is mapped as a normal table only with the tag #View instead.
I did the same on my projects.
You can call native queries from JPA, for example:
Query q = em.createNativeQuery("SELECT p.firstname, p.lastname FROM Person p");
List<Object[]> persons= q.getResultList();
for (Object[] p : persons) {
System.out.println("Person "
+ p[0]
+ " "
+ p[1]);
}
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<MessageWrapper> q = cb.createQuery(MessageWrapper.class);
Root<Chain> c = q.from(Chain.class);
Join<Chain, Message> m = p.join("messages");
q.groupBy(c.get("id"));
q.select(cb.construct(MessageWrapper.class, c.get("id"), cb.max(m.get("id"))));

Categories