java.lang.ClassCastException using JPA Queries - java

I'm trying to create Java EE web aplication but I have problem getting single result from database. Getting list of results isn't a problem.
public UserCredentialsDTO findByUsernameAndPassword(String username, String password) {
EntityManager em = getEntityManager();
TypedQuery<UserCredentialsDTO> q = em.createNamedQuery("UserCredentialsDTO.findByUsernameAndPassword", UserCredentialsDTO.class);
//Query q = em.createNamedQuery("UserCredentialsDTO.findByUsernameAndPassword", UserCredentialsDTO.class);
q.setParameter("un", username);
q.setParameter("pw", password);
UserCredentialsDTO r = null;
try{
r = q.getSingleResult(); //This line is a problem
//r = (UserCredentialsDTO)q.getSingleResult();
} catch(javax.persistence.NoResultException e) {
}
return r;
}
Using both Query and TypedQuery throws java.lang.ClassCastException
java.lang.ClassCastException: wipb.jee.clientdemo.model.UserCredentialsDTO cannot be cast to wipb.jee.clientdemo.model.UserCredentialsDTO
EDIT
UserCredentialsDTO:
#NamedQueries(
{#NamedQuery(name = "UserCredentialsDTO.findByUsernameAndPassword", query = "select uc from UserCredentialsDTO uc where uc.username=:un and uc.password=:pw")}
)
#Entity
#Table(name="USERCREDENTIALS", schema="APP")
public class UserCredentialsDTO implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
#OneToMany(mappedBy = "userCredentials", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<UserGroupDTO> userGroups = new LinkedList<>();
//getters and setters
public void add(UserGroupDTO userGroup) {
userGroup.setUserCredentials(this);
this.userGroups.add(userGroup);
}
public List<UserGroupDTO> getUserGroups() {
return userGroups;
}
}

This looks like an environment issue, where different classloaders are being used for JPA and the rest of the application.
Refer to this thread

Related

JPA Native Query Result Set Mapping to Entity class having child class

(column and variable name changed after posting question)i am writing join query using entityManager.createNativeQuery(somequery) in jpa custom method when i run code i get following error :
com.ibm.db2.jcc.am.SqlException: [jcc][10150][10300][4.12.56] Invalid >parameter: Unknown column name exc_seq_nbr. ERRORCODE=-4460, SQLSTATE=null
i am using IBM DB2 server and spring boot
exceptionTenderPK (object in entity class) is not being mapped correctly thats why getting invalid column can someone please tell me how to map exceptionTenderPK object class
Note: i cant use #OneToMany in this case because tables are unrelated
#Entity
#Table(name = "Table_name")
#Data
public class MainPojoclass {
#EmbeddedId
#JsonProperty(value = "mainPojoclassPK")
private MainPojoclassPK mainPojoclassPK;
#Column(name = "amt")
#JsonProperty(value = "amt")
private BigDecimal amt;
#Column(name = "tndid")
#JsonProperty(value = "tndid")
private String tndid;
#Column(name = "cde")
#JsonProperty(value = "cde")
private String cde;
#Column(name = "ind")
#JsonProperty(value = "ind")
private String ind;
#Column(name = "user")
#JsonProperty(value = "user")
private String user;
#Column(name = "updatedtime")
#JsonProperty(value = "updatedtime")
private Date updatedtime;
#Column(name = "src")
#JsonProperty(value = "src")
private String src;
#Column(name = "stat")
#JsonProperty(value = "stat")
private String stat;
}
#Transactional
public interface JoinQueryRepository extends JpaRepository<MainPojoclass, Long>, JoinQueryRepositoryCustom{
}
public interface JoinQueryRepositoryCustom {
List<MainPojoclass> getGRDetails(MainPojoclass et,Date reportDate);
}
public class JoinQueryRepositoryImpl implements JoinQueryRepositoryCustom {
#PersistenceContext
EntityManager entityManager;
#SuppressWarnings("all")
#Override
public List<MainPojoclass> getGRDetails(MainPojoclass et,Date rdate) {
String queryStr = "select et.Salss_DTE from table et"
+ " join dte etr on et.Salss_DTE = etr.Salss_DTE where et.nbr =? ";
List<MainPojoclass> datalist = null;
Query query = entityManager.
createNativeQuery(queryStr,"mapping")
.setParameter(1, 222);
datalist = query.getResultList();
return datalist;
}
}
The error says that there is no column exc_seq_nbr and you used that in your EntityResult mapping.
In your query you only return et.SLS_DTE you have to return all columns that are in the result set mapping.
Hi all since i am not getting any solutions i am going with below solution it works for me and removing #SqlResultSetMapping below code is working without sql result set mapping
Query q = em.createNativeQuery(queryStr);
List<Object[]> resultList = q.getResultList();
for (Object[] result : resultList) {
entityObj.setReason(result[0].toString);
//rest attribute will convert from result[1].toString to corresponding
// data type and set to entity object
}

cant get a resultList from a Java NamedQuery

#Override
public com.iranatelier.sistema.dominio.Probandoblob pruebaBajarImagen() throws Exception{
com.iranatelier.sistema.dominio.Probandoblob a = new com.iranatelier.sistema.dominio.Probandoblob();
Probandoblob b = new Probandoblob();
try {
Query query = en.createNamedQuery("Probandoblob.findAll");
List lista = query.getResultList();
if (lista.size() > 0) {
for(Object c : lista){
b = (Probandoblob) c;
a.setId(b.getId());
a.setImagen(b.getImagen());
}
}
} catch (Exception e) {
throw new Exception("Error en editarEntrega:", e);
}
return a;
}
i have a sql oracle table whit a blob data type, when i try to get a result of a select from database, sendme this error.
Exception Description: Could not deserialize object from byte array.
Internal Exception: java.io.StreamCorruptedException: invalid stream header: FFD8FFE0
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[imagen-->JAAN.PROBANDOBLOB.IMAGEN]
Descriptor: RelationalDescriptor(com.iranatelier.sistema.entities.Probandoblob --> [DatabaseTable(JAAN.PROBANDOBLOB)])>
the entity are :
#Entity
#Table(name = "PROBANDOBLOB", catalog = "", schema = "JAAN")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Probandoblob.findAll", query = "SELECT p FROM Probandoblob p")
, #NamedQuery(name = "Probandoblob.findById", query = "SELECT p FROM Probandoblob p WHERE p.id = :id")})
public class Probandoblob implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private BigDecimal id;
#Basic(optional = false)
#NotNull
#Lob
#Column(name = "IMAGEN")
private byte[] imagen;
how i can download a blob type from a data base?

Jpa Criteria API, Dynamic Predicates with #OneTomany relation

Here are my Entities.
TradeItem.class
#Entity
#Table(name = "TRADEITEMS")
public class TradeItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "TRADEITEM_ID")
private Long id;
private String shopOwner;
private Boolean corrupted;
private String base;
private String type;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Mod> mod;
private String league;
...
}
Mod.class
#Entity
#Table(name = "MODS")
public class Mod {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Double miniValue;
private Double maxiValue;
private String modName;
...
}
DaoImpl
#Repository
public class TradeItemDaoImp implements TradeItemDao{
#PersistenceContext
private EntityManager em;
#Override
public Optional<List<TradeItem>> search(TradeItemRequest request) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<TradeItem> cq = criteriaBuilder.createQuery(TradeItem.class);
Root<TradeItem> root = cq.from(TradeItem.class);
List<Predicate> predicates = new LinkedList<>();
predicates.add(criteriaBuilder.equal(root.get("league"), request.getLeague()));
if(request.getName() != null){
predicates.add(criteriaBuilder.like(root.get("name"), "%"+request.getName()+"%"));
}
if(request.getType() != null){
predicates.add(criteriaBuilder.equal(root.get("type"), request.getType()));
}
if(request.getBase() != null) {
predicates.add(criteriaBuilder.equal(root.get("base"), request.getBase()));
}
if(request.getIdentified() != null){
predicates.add(criteriaBuilder.equal(root.get("identified"), request.getIdentified()));
}
if(request.getCorrupted() != null){
predicates.add(criteriaBuilder.equal(root.get("corrupted"), request.getCorrupted()));
}
if(request.getMods().size() > 0) {
Join<TradeItem, Mod> mod = root.joinSet("mod");
for (ModRequest m : request.getMods()) {
predicates.add(
criteriaBuilder.and(
criteriaBuilder.equal(mod.get("modName"), m.getName()),
criteriaBuilder.ge(mod.get("miniValue"), m.getMinValue() == null ? 0 : m.getMinValue()),
criteriaBuilder.le(mod.get("maxiValue"), m.getMaxValue() == null ? 10000 : m.getMaxValue()))
);
}
}
cq.select(root)
.where(predicates.toArray(new Predicate[predicates.size()]));
TypedQuery<TradeItem> typedQuery = em.createQuery(cq);
return Optional.of(
typedQuery
.setFirstResult(0)
.setMaxResults(50)
.getResultList());
}
}
Basicly what i am trying to do here is that i have developed a Webscraper for a specific Tradingforum. I have a webapplication where you can search for forum-items through a form. Now each TradingItem contains a set of mods(#OneToMany) which have different names and values.
When i search for an item with only one or zero mods, it works fine. But as soon as i add two or more mods in the search-form, it returns an empty list.
I'm new to the Criteria Api and there is obviously something wrong with my mod-predicates/logic.
I'm using hibernate 5.1.0 & MySql
Example of form
Edit: Solved
I simply had to move the Join to inside the for-loop.
for (ModRequest m : request.getMods()) {
Join<TradeItem, Mod> mod = root.joinSet("mod");
predicates.add(
criteriaBuilder.and(
criteriaBuilder.equal(mod.get("modName"), m.getName()),
criteriaBuilder.ge(mod.get("miniValue"), m.getMinValue() == null ? 0 : m.getMinValue()),
criteriaBuilder.le(mod.get("maxiValue"), m.getMaxValue() == null ? 10000 : m.getMaxValue()))
);
}

Hibernate Error SQLGrammarException (MySQL)

I try to get back a list of elements in an instance Criteria. In the execution I obtain this exception. What is the problem ?
The name of my database is "TransPlusBD".
The name of my table is a "gerant".
But the error indicates me that he(it) does not find the table "TransPlusDB.gerant_gerant", yet this table does not exist.
Normally we have to have his "TransPlusDB.gerant".
Code of the configuration
properties = new Properties();
properties.put("hibernate.dialect","org.hibernate.dialect.MySQLInnoDBDialect");
properties.put("hibernate.connection.driver_class","com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url","jdbc:mysql://(cloud amazone aws).amazonaws.com:3306/TransPlusDB");
properties.put("hibernate.connection.username","xxx");
properties.put("hibernate.connection.password","xxxxxxxxxxxx");
properties.put("hibernate.connection.pool_size","4");
configuration = new Configuration();
configuration.setProperties(properties);
configuration.addAnnotatedClass(Administrator.class);
configuration.addAnnotatedClass(AutoGare.class);
configuration.addAnnotatedClass(Car.class);
configuration.addAnnotatedClass(City.class);
configuration.addAnnotatedClass(Company.class);
configuration.addAnnotatedClass(transplus.models.Configuration.class);
configuration.addAnnotatedClass(DateDeparture.class);
configuration.addAnnotatedClass(Departure.class);
configuration.addAnnotatedClass(HoursDeparture.class);
configuration.addAnnotatedClass(Luggage.class);
configuration.addAnnotatedClass(Manager.class);
configuration.addAnnotatedClass(Passenger.class);
configuration.addAnnotatedClass(PlanningVoyage.class);
configuration.addAnnotatedClass(Route.class);
configuration.addAnnotatedClass(Stopover.class);
configuration.addAnnotatedClass(SysAdmin.class);
configuration.addAnnotatedClass(Ticket.class);
configuration.addAnnotatedClass(TypeCar.class);
configuration.addAnnotatedClass(ModificationLuggage.class);
configuration.addAnnotatedClass(ModificationTicket.class);
configuration.addAnnotatedClass(PassageRoute.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
Code of my class
#Entity
#Table(name = "gerant")
public class Manager implements Serializable // Table Gerant
{
#Id
#GeneratedValue
#Column(name = "code_gerant")
private long code_manager;
#Column(name = "matricule_gérant",unique = true)
private String matricule_manager;
#Column(name = "nom_gerant")
private String lastName_manager;
#Column(name = "prenom_gerant")
private String firstName_manager;
#Column(name = "password_gerant",nullable = false)
private String password_manager;
#Column(name = "login_gerant",unique = true,nullable = false)
private String login_manager;
#Column(name = "poste_gerant")
private String function_manager;
#Column(name = "actif_gerant")
private boolean enabled_manager;
#Enumerated(EnumType.ORDINAL)
#Column(name = "privilege_gerant")
private Privilege privilege;
#ManyToOne
#JoinColumn(name = "code_manager", foreignKey = #ForeignKey(name = "fk_gerant_manager"))
private Administrator administrator;
#ManyToOne
#JoinColumn(name = "over_gerant", foreignKey = #ForeignKey(name = "fk_over_gerant"))
private Manager overManager;
#Expose // Annotation for Gson
#OneToMany(cascade = CascadeType.ALL,orphanRemoval = false)
private List<Manager> underManagers = new ArrayList<>();
Code for the recovery of the list.
public String getAllManager()
{
if(session.isOpen())
{
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
transaction.begin();
Criteria criteria = session.createCriteria(Manager.class);
List list = criteria.list();
transaction.commit();
if(list != null)
{
if(!list.isEmpty())
return serializeTab(list);
}
return null;
}
catch (Exception e)
{
if(transaction != null)
transaction.rollback();
e.printStackTrace();
}
}
return null;
}
Here is the raised exception
this = {ServiceManager#3681}
transaction = {TransactionImpl#3683}
transactionCoordinator = {JdbcResourceLocalTransactionCoordinatorImpl#3979}
transactionDriverControl = {JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl#3980}
valid = false
e = {SQLGrammarException#3954} "org.hibernate.exception.SQLGrammarException: could not extract ResultSet"
sqlException = {MySQLSyntaxErrorException#3958} "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'TransPlusDB.gerant_gerant' doesn't exist"
SQLState = "42S02"
vendorCode = 1146
next = null
detailMessage = "Table 'TransPlusDB.gerant_gerant' doesn't exist"
cause = {MySQLSyntaxErrorException#3958} "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'TransPlusDB.gerant_gerant' doesn't exist"
stackTrace = {StackTraceElement[0]#3961}
suppressedExceptions = {Collections$UnmodifiableRandomAccessList#3962} size = 0
sql = "n/a"
Help I PLEASE
The table gerant_gerant is a join table for a self association for this
#OneToMany(cascade = CascadeType.ALL,orphanRemoval = false)
private List<Manager> underManagers = new ArrayList<>();
You need to let Hibernate to create this table using the hibernate.hbm2ddl.auto property or you can create it manually with constraints ( a foreign key, a unique key).
You can specify a join table name with the #JoinTable annotation.
I added this line of code at the level of the configuration
properties.put("hbm2ddl.auto","validate");
Then this code at the level of my class
#OneToMany(cascade = CascadeType.ALL,orphanRemoval = false,mappedBy = "overManager")
private List<Manager> underManager;
Thank

Spring-MVC, Hibernate : Creating DTO objects from Domain objects

I am working on a Spring-MVC application in which I am trying to search for List of GroupNotes in database. The mapping in my project is GroupCanvas has one-to-many mapping with GroupSection and GroupSection has one-to-many mapping with GroupNotes. Because of these mappings, I was getting LazyInitializationException. As suggested on SO, I should be converting the objects to a DTO objects for transfer. I checked on net, but couldnt find a suitable way to translate those.
I have just created a new List to avoid the error, but one field is still giving me an error. I would appreciate if anyone tells me either how to fix this error or convert the objects to a DTO objects so they can be transferred.
Controller code :
#RequestMapping(value = "/findgroupnotes/{days}/{canvasid}")
public #ResponseBody List<GroupNotes> findGroupNotesByDays(#PathVariable("days")int days, #PathVariable("canvasid")int canvasid){
List<GroupNotes> groupNotesList = this.groupNotesService.findGroupNotesByDays(days,canvasid);
List<GroupNotes> toSendList = new ArrayList<>();
for(GroupNotes groupNotes : groupNotesList){
GroupNotes toSendNotes = new GroupNotes();
toSendNotes.setMnotecolor(groupNotes.getMnotecolor());
toSendNotes.setNoteCreationTime(groupNotes.getNoteCreationTime());
toSendNotes.setMnotetag(groupNotes.getMnotetag());
toSendNotes.setMnotetext(groupNotes.getMnotetext());
toSendNotes.setAttachCount(groupNotes.getAttachCount());
toSendNotes.setNoteDate(groupNotes.getNoteDate());
toSendList.add(toSendNotes);
}
return toSendList;
}
GroupNotesDAOImpl :
#Override
public List<GroupNotes> searchNotesByDays(int days, int mcanvasid) {
Session session = this.sessionFactory.getCurrentSession();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -days);
long daysAgo = cal.getTimeInMillis();
Timestamp nowMinusDaysAsTimestamp = new Timestamp(daysAgo);
GroupCanvas groupCanvas = (GroupCanvas) session.get(GroupCanvas.class,mcanvasid);
Query query = session.createQuery("from GroupSection as n where n.currentcanvas.mcanvasid=:mcanvasid");
query.setParameter("mcanvasid", mcanvasid);
List<GroupSection> sectionList = query.list();
List<GroupNotes> notesList = new ArrayList<GroupNotes>();
for (GroupSection e : sectionList) {
System.out.println("Section name is "+e.getMsectionname());
GroupSection groupSection = (GroupSection) session.get(GroupSection.class,e.getMsectionid());
Query query1 = session.createQuery("from GroupNotes as gn where gn.ownednotes.msectionid=:msectionid and gn.noteCreationTime >:limit");
query1.setParameter("limit", nowMinusDaysAsTimestamp);
query1.setParameter("msectionid",e.getMsectionid());
notesList.addAll(query1.list());
}
// I am getting the data below, but I get JSON errors.
for(GroupNotes groupNotes : notesList){
System.out.println("Group notes found are "+groupNotes.getMnotetext());
}
return notesList;
}
GroupCanvas model :
#Entity
#Table(name = "membercanvas")
public class GroupCanvas{
#OneToMany(mappedBy = "currentcanvas",fetch=FetchType.LAZY, cascade = CascadeType.REMOVE)
#JsonIgnore
private Set<GroupSection> ownedsection = new HashSet<>();
#JsonIgnore
public Set<GroupSection> getOwnedsection() {
return this.ownedsection;
}
public void setOwnedsection(Set<GroupSection> ownedsection) {
this.ownedsection = ownedsection;
}
}
GroupSection model :
#Entity
#Table(name = "membersection")
public class GroupSection{
#OneToMany(mappedBy = "ownednotes", fetch = FetchType.EAGER,cascade = CascadeType.REMOVE)
#JsonIgnore
private Set<GroupNotes> sectionsnotes = new HashSet<>();
public Set<GroupNotes> getSectionsnotes(){
return this.sectionsnotes;
}
public void setSectionsnotes(Set<GroupNotes> sectionsnotes){
this.sectionsnotes=sectionsnotes;
}
}
GroupNotes model :
#Entity
#Table(name="groupnotes")
public class GroupNotes{
#Id
#Column(name="mnoteid")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "mnote_gen")
#SequenceGenerator(name = "mnote_gen",sequenceName = "mnote_seq")
#org.hibernate.annotations.Index(name = "mnoticesidindex")
private int mnoticesid;
#Column(name = "mnotetext")
private String mnotetext;
#Column(name = "mnoteheadline")
private String mnotetag;
#Column(name = "mnotecolor")
private String mnotecolor;
#Column(name = "mnoteorder")
private double mnoteorder;
#Column(name = "attachmentcount")
private int attachCount;
#Column(name = "notedate")
private String noteDate;
#Column(name = "uploader")
private String uploader;
#Column(name = "activeedit")
private boolean activeEdit;
#Column(name = "notedisabled")
private boolean noteDisabled;
#Column(name = "noteinactive")
private boolean noteInActive;
#Column(name = "notecreatoremail")
private String noteCreatorEmail;
#Column(name = "prefix")
private String prefix;
#Column(name = "timestamp")
private Timestamp noteCreationTime;
#Transient
private boolean notRead;
#Transient
private String tempNote;
#Transient
private String canvasUrl;
#ManyToOne
#JoinColumn(name = "msectionid")
#JsonIgnore
private GroupSection ownednotes;
#JsonIgnore
public GroupSection getOwnednotes(){return this.ownednotes;}
public void setOwnednotes(GroupSection ownednotes){this.ownednotes=ownednotes;}
#JsonIgnore
public int getOwnedSectionId(){
return this.ownednotes.getMsectionid();
}
#OneToMany(mappedBy = "mnotedata",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
#JsonIgnore
private Set<GroupAttachments> mattachments = new HashSet<>();
public Set<GroupAttachments> getMattachments() {
return this.mattachments;
}
public void setMattachments(Set<GroupAttachments> mattachments) {
this.mattachments = mattachments;
}
#OneToMany(mappedBy = "mhistory",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
#JsonIgnore
private Set<GroupNoteHistory> groupNoteHistorySet = new HashSet<>();
public Set<GroupNoteHistory> getGroupNoteHistorySet(){
return this.groupNoteHistorySet;
}
public void setGroupNoteHistorySet(Set<GroupNoteHistory> groupNoteHistorySet){
this.groupNoteHistorySet = groupNoteHistorySet;
}
#OneToMany(mappedBy = "unreadNotes",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
#JsonIgnore
private Set<UnreadNotes> unreadNotesSet = new HashSet<>();
public Set<UnreadNotes> getUnreadNotesSet(){
return this.unreadNotesSet;
}
public void setUnreadNotesSet(Set<UnreadNotes> unreadNotesSet){
this.unreadNotesSet = unreadNotesSet;
}
//getters and setters ignored
}
Error log :
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.journaldev.spring.model.GroupNotes["ownedSectionId"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.journaldev.spring.model.GroupNotes["ownedSectionId"])
Kindly let me know what to do, as I am stuck on that error since some time.
What I think that happens is Jackson tries to serialize all fields in the hierarchy based on getter methods. In some situation NullPointerException is thrown in the following method:
#JsonIgnore
public int getOwnedSectionId(){
return this.ownednotes.getMsectionid();
}
replace it with the following method:
#JsonIgnore
public int getOwnedSectionId(){
if(this.ownednotes != null)
return this.ownednotes.getMsectionid();
return 1;
}
I don't have an explanation why jackson tries to serialize it when is market with #JsonIgnore but you can give a try with my proposal
I would appreciate if anyone tells me either how to fix this error or convert the objects to a DTO objects so they can be transferred.
We use DozerMapper at work for this purpose.
Instead of doing that mapping manually you might want to take a look at Blaze-Persistence Entity Views which can be used to efficiently implement the DTO pattern with JPA. Here a quick code sample how your problem could be solved
First you define your DTO as entity view
#EntityView(GroupNotes.class)
public interface GroupNoteView {
#IdMapping("mnoticesid") int getId();
String getMnotecolor();
String getMnotetag();
String getMnotetext();
String getNoteDate();
Timestamp getNoteCreationTime();
int getAttachCount();
}
Next you adapt your DAO to make use of it
#Override
public List<GroupNoteView> searchNotesByDays(int days, int mcanvasid) {
EntityManager entityManager = // get the entity manager from somewhere
CriteriaBuilderFactory cbf = // factory for query building from Blaze-Persistence
EntityViewManager evm = // factory for applying entity views on query builders
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -days);
long daysAgo = cal.getTimeInMillis();
Timestamp nowMinusDaysAsTimestamp = new Timestamp(daysAgo);
CriteriaBuilder<GroupNotes> cb = cbf.create(entityManager, GroupNotes.class, "note")
.where("noteCreationTime").gt(nowMinusDaysAsTimestamp)
.where("ownednotes.ownedcanvas.mcanvasid").eq(mcanvasid);
return evm.applySetting(EntityViewSetting.create(GroupNoteView.class), cb)
.getResultList();
}
And finally the calling code
#RequestMapping(value = "/findgroupnotes/{days}/{canvasid}")
public #ResponseBody List<GroupNoteView> findGroupNotesByDays(#PathVariable("days")int days, #PathVariable("canvasid")int canvasid){
return this.groupNotesService.findGroupNotesByDays(days, canvasid);
}

Categories