How to order descending the data in hibernate - java

I want to order the data descending in hibernate,
but not working at all,
this is my code,
#SuppressWarnings("unchecked")
#Override
public List<MPNValas> listAllMPNValas() throws Exception{
DetachedCriteria criteria = DetachedCriteria.forClass(MPNValas.class);
criteria.addOrder(Order.desc("ID"));
List<MPNValas> mpnvalasList = getHibernateTemplate().findByCriteria(criteria);
return mpnvalasList;
}
this is my controller,
#RequestMapping("/admin/mpn-valas.html")
public ModelAndView listMPNValas(ModelMap model)throws Exception
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String sessionUser = user.getUsername();
try{
UserAdmin dataUser = userService.get(sessionUser);
model.addAttribute("userData", dataUser);
} catch(Exception e){
e.printStackTrace();
}
ModelAndView mav = new ModelAndView("mpnvalas");
List<MPNValas> mpnvalas = mpnvalasService.listAllMPNValas();
mav.addObject("mpnvalas", mpnvalas);
return mav;
}
and this is the class,
package prod.support.model.gwprod;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="LOOKUP")
public class MPNValas {
private Integer ID;
private String TIPE;
private String KODE_PERUSAHAAN;
private String CODE;
private String NAME;
private String VALUE;
#Id
#Column(name="ID", unique=true, nullable=false)
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
#Column(name="TIPE")
public String getTIPE() {
return TIPE;
}
public void setTIPE(String TIPE) {
this.TIPE = TIPE;
}
#Column(name="KODE_PERUSAHAAN")
public String getKODE_PERUSAHAAN() {
return KODE_PERUSAHAAN;
}
public void setKODE_PERUSAHAAN(String KODE_PERUSAHAAN) {
this.KODE_PERUSAHAAN = KODE_PERUSAHAAN;
}
#Column(name="CODE")
public String getCODE() {
return CODE;
}
public void setCODE(String CODE) {
this.CODE = CODE;
}
#Column(name="NAME")
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME;
}
#Column(name="VALUE")
public String getVALUE() {
return VALUE;
}
public void setVALUE(String VALUE) {
this.VALUE = VALUE;
}
/**
* #param args
*/
}
and this the list of data
that I miss something??
any help will be pleasure :))

You miss nothing, just note that the argument to the desc method is case sensitive and should match the name of the attribute to sort by.
Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.desc("id"));

Related

ebean model update not permanent

Good day! I'm having a problem when updating an entity. When I click the "update" button, the changes are saved. However, when I go a different page, the recently changed (or added) items are there but the old items (that should be changed or removed) are also there. Particularly the relatedTags (the name and notes are updating just fine). Why is it not persistent or permanent?
Here is where the updating happens.
Form<Tag> filledForm = tagForm.fill(Tag.find.byId(id)).bindFromRequest();
Tag editedTag = RelatedTag.findTag(id);
if(filledForm.hasErrors()) {
return badRequest(editTagForm.render(user, editedTag, filledForm, tags));
}
else {
List<RelatedTag> relatedTagsAlloc = new ArrayList<RelatedTag>();
java.util.Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] relatedTags = map.get("relatedTags.tag.name");
String[] relationship = map.get("relatedTags.relationship");
String[] relatedNotes = map.get("relatedTags.relatedNotes");
if (relatedTags != null) {
for (int i = 0; i < relatedTags.length; i++) {
if (RelatedTag.exists(relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "))) {
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
} else {
Tag unknown = new Tag(relatedTags[i], "");
Tag.create(unknown);
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
}
}
editedTag.getRelatedTags().clear();
}
editedTag.setName(filledForm.get().getName().toLowerCase().replaceAll("\\s+", " "));
editedTag.setRelatedTags(relatedTagsAlloc);
editedTag.update();
Application.log(user, editedTag, action);
writeToFile(editedTag);
return ok(summary.render(user, editedTag));
}
And here are the models:
Tag model:
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class Tag extends Model{
#Id
private int id;
#Required
#MaxLength(value=100)
#Column(unique=true)
private String name;
#MaxLength(value=200)
private String notes;
#OneToMany(cascade=CascadeType.ALL)
public List<RelatedTag> relatedTags = new ArrayList<RelatedTag>();
#Version
public Timestamp lastUpdate;
public static Finder<Integer, Tag> find = new Finder(Int.class, Tag.class);
public Tag() {
}
public Tag(String name, String notes){
this.name = name;
this.notes = notes;
}
public Tag(int id, String name, String notes, List<RelatedTag> relatedTags) {
this.id = id;
this.name = name;
this.notes = notes;
this.relatedTags = relatedTags;
}
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 getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public List<RelatedTag> getRelatedTags() {
return relatedTags;
}
public void setRelatedTags(List<RelatedTag> relatedTags) {
this.relatedTags = relatedTags;
}
public static List<Tag> all() {
return find.all();
}
public static void create(Tag tag){
tag.save();
}
public static void delete(int id){
find.ref(id).delete();
}
public static void update(int id, Tag tag) {
tag.update(id); // updates this entity, by specifying the entity ID
}
public static boolean exists(Tag newTag) {
for(Tag allTags : Tag.find.all()) {
if(allTags.getName().equals(newTag.getName()))
return true;
}
return false;
}
}
RelatedTag model
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class RelatedTag extends Model {
#Id
public int rtID;
private int id; //same as Tag's id
private String relationship;
private String relatedNotes;
#Version
public Timestamp lastUpdate;
public RelatedTag() {}
public RelatedTag(int id, String relationship, String relatedNotes) {
this.id = id;
this.relationship = relationship;
this.relatedNotes = relatedNotes;
}
public void setId(int id){
this.id = id;
}
public void setRelationship(String relationship){
this.relationship = relationship;
}
public void setRelatedNotes(String relatedNotes) {
this.relatedNotes = relatedNotes;
}
public int getId(){
return id;
}
public String getRelationship(){
return relationship;
}
public String getRelatedNotes() {
return relatedNotes;
}
public static void create(List<RelatedTag> rt){
((Model) rt).save();
}
public static boolean exists(String tagRelated) {
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName()))
return true;
}
return false;
}
public static RelatedTag findByLabel(String tagRelated, String relation, String relatedNotes) {
RelatedTag relatedTag = null;
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName())) {
relatedTag = new RelatedTag(tag.getId(), relation, relatedNotes);
}
}
return relatedTag;
}
public static Tag findTag(int id) {
for(Tag tag : Tag.find.all()) {
if(id == tag.getId())
return tag;
}
return null;
}
}
What have I been doing wrong? Please help me fix this. Thank you very much!

java.util.Arrays$ArrayList cannot be cast to java.lang.String on hibernate restriction

I've been staring at this issue for too long. When executing the .list() line spring throws an exception with regards to the .add(Restrictions.in("LocationCode", locations))
java.util.Arrays$ArrayList cannot be cast to java.lang.String.
Restrictions.in is expecting (string, Object[]) no??
Can someone point out what I'm missing when passing in to the Restrictions.in??
public List getIDsByDivision(String SelectedAccountCode,
List SelectedDivision, String SelectedLocation) {
List IDs=null;
String result="--Select--";
Session session=null;
String[] locations=SelectedLocation.split(",");
try
{
session=sessionFactory.openSession();
if(null!=SelectedAccountCode && !SelectedAccountCode.equals("--Select--")
&&SelectedDivision.size()>0&&!SelectedDivision.equals("--Select--")
&&locations.length>0&&!SelectedLocation.equals("--Select--"))
{
IDs=session.createCriteria(Customer.class)
// TODO fix this to location
.setProjection(Projections.distinct(Projections.property("ID")))
.add(Restrictions.eq("AcctCode", SelectedAccountCode))
.add(Restrictions.eq("Division", SelectedDivision))
.add(Restrictions.in("LocationCode", locations ))
.list();
}
Customer class
package <removed>;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Customer {
#Id
private String ID;
#Column
private String Name;
private String AcctCode;
private String LocationCode;
private String Division;
private String ContactEmail;
public Customer(){}
public Customer(String iD, String name, String acctCode,
String locationCode, String division, String contactEmail) {
super();
ID = iD;
Name = name;
AcctCode = acctCode;
LocationCode = locationCode;
Division = division;
ContactEmail=contactEmail;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAcctCode() {
return AcctCode;
}
public void setAcctCode(String acctCode) {
AcctCode = acctCode;
}
public String getLocationCode() {
return LocationCode;
}
public void setLocationCode(String locationCode) {
LocationCode = locationCode;
}
public String getDivision() {
return Division;
}
public void setDivision(String division) {
Division = division;
}
public String getContactEmail() {
return ContactEmail;
}
public void setContactEmail(String contactEmail) {
ContactEmail = contactEmail;
}
}
Semi-false positive on what the issue was, the following works(I need to refactor, but hopefully the gist is understood):
String[] locations=SelectedLocation.split(",");
List<String> locs=new ArrayList<String>();
for(String l:locations)
{
locs.add(l);
}
...
The exception was actually referring to:
.add(Restrictions.in("Division", SelectedDivision))
(adding this for completeness)
.add(Restrictions.in("LocationCode", locs.toArray(new String[locs.size()]) ))

How to write query in hibernate(HQL) to perform 2 joins without mapping?

I want to convert the following query into HQL:
SELECT C.ID, E.DESCRIPTION as STATUS, E1.DESCRIPTION as SUBJECT
FROM CRED C
join CODE_EVN E
ON E.CODE = C.STATUS_CODE
AND E.SUBCODE = C.STATUS_SUBCODE
join CODE_EVN E1
ON E1.CODE = C.SUBJECT_CODE
AND E1.SUBCODE = C.SUBJECT_SUBCODE
I have two classes User and Codes with no mapping in between them, so how do I execute the following query in Hibernate?
I have tried out many things but nothing seems to work
These are my 2 bean classes:
User class:
#Entity
#Table(name="CRED")
public class User {
private String id;
private String STATUS_CODE;
private String STATUS_SUBCODE;
private String SUBJECT_CODE;
private String SUBJECT_SUBCODE;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setSTATUS_CODE(String sTATUS_CODE) {
STATUS_CODE = sTATUS_CODE;
}
public String getSTATUS_CODE() {
return STATUS_CODE;
}
public void setSTATUS_SUBCODE(String sTATUS_SUBCODE) {
STATUS_SUBCODE = sTATUS_SUBCODE;
}
public String getSTATUS_SUBCODE() {
return STATUS_SUBCODE;
}
public void setSUBJECT_CODE(String sUBJECT_CODE) {
SUBJECT_CODE = sUBJECT_CODE;
}
public String getSUBJECT_CODE() {
return SUBJECT_CODE;
}
public void setSUBJECT_SUBCODE(String sUBJECT_SUBCODE) {
SUBJECT_SUBCODE = sUBJECT_SUBCODE;
}
public String getSUBJECT_SUBCODE() {
return SUBJECT_SUBCODE;
}
}
Codes class:
#Entity
#Table(name="CODE_EVN")
public class Codes {
#Id
private String CODE;
private String SUBCODE;
private String DESCRIPTION;
public void setCODE(String cODE) {
CODE = cODE;
}
public String getCODE() {
return CODE;
}
public void setSUBCODE(String sUBCODE) {
SUBCODE = sUBCODE;
}
public String getSUBCODE() {
return SUBCODE;
}
public void setDESCRIPTION(String dESCRIPTION) {
DESCRIPTION = dESCRIPTION;
}
public String getDESCRIPTION() {
return DESCRIPTION;
}
}

jax-rs response.getEntity not working

I want to use javax.ws.rs.core.Response to send and receive an Card entity object. But I don't know how to convert the contents back in to a Card object.
My testCreate() method should execute the create(Card card) method, receive back the json and convert it in to a card object. But I somehow always get type mismatches or it says that the getEntity() method can't be executed like this: response.getEntity(Card.class).
Does anybody know how I have to handle the response correctly so that I can convert the returned json entity in to a Card object again?
Here my CardResource method:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response create(Card card) {
Card c = dao.create(card);
if(c.equals(null)) {
return Response.status(Status.BAD_REQUEST).entity("Create failed!").build();
}
return Response.status(Status.OK)
.entity(c)
.type(MediaType.APPLICATION_JSON)
.build();
}
And here my CardResourceTests class
#Test
public void testCreate() {
boolean thrown = false;
CardResource resource = new CardResource();
Card c = new Card(1, "Cardname", "12345678", 1, 1,
"cardname.jpg", new Date(), new Date());
try {
Response result = resource.create(c);
System.out.println(result.getEntity(Card.class)); // not working!!!
if(result.getStatus() != 200) {
thrown = true;
}
} catch(Exception e) {
e.printStackTrace();
thrown = true;
}
assertEquals("Result", false, thrown);
}
And here my Card.class
#XmlRootElement
#PersistenceCapable(detachable="true")
public class Card {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private Integer id;
#Persistent
private String name;
#Persistent
private String code;
#Persistent
private Integer cardProviderId;
#Persistent
private Integer codeTypeId;
#Persistent
private String picturePath;
#Persistent
private Boolean valid;
#Persistent
private Date mobCreationDate;
#Persistent
private Date mobModificationDate;
#Persistent
private Date creationDate;
#Persistent
private Date modificationDate;
public Card() {
this.setId(null);
this.setName(null);
this.setCode(null);
this.setCardProviderId(null);
this.setCodeTypeId(null);
this.setPicturePath(null);
this.setMobCreationDate(null);
this.setMobModificationDate(null);
this.setCreationDate(null);
this.setModificationDate(null);
}
public Card(Integer id, String name, String code, Integer cardProviderId,
Integer codeTypeId, String picturePath,
Date mobCreationDate, Date mobModificationDate) {
this.setId(id);
this.setName(name);
this.setCode(code);
this.setCardProviderId(cardProviderId);
this.setCodeTypeId(codeTypeId);
this.setPicturePath(picturePath);
this.setMobCreationDate(mobCreationDate);
this.setMobModificationDate(mobModificationDate);
this.setCreationDate(new Date());
this.setModificationDate(new Date());
}
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public Integer getCardProviderId() {
return cardProviderId;
}
public void setCardProviderId(Integer cardProviderId) {
this.cardProviderId = cardProviderId;
}
public void setCode(String code) {
this.code = code;
}
public Integer getCodeTypeId() {
return codeTypeId;
}
public void setCodeTypeId(Integer codeTypeId) {
this.codeTypeId = codeTypeId;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public Date getMobCreationDate() {
return mobCreationDate;
}
public void setMobCreationDate(Date mobCreationDate) {
this.mobCreationDate = mobCreationDate;
}
public Date getMobModificationDate() {
return mobModificationDate;
}
public void setMobModificationDate(Date mobModificationDate) {
this.mobModificationDate = mobModificationDate;
}
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
}
And here my CardDAO class
public class CardDAO {
private final static Logger logger = Logger.getLogger(CardDAO.class.getName());
public Card create(Card card) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Card c = new Card(card.getId(), card.getName(), card.getCode(),
card.getCardProviderId(), card.getCodeTypeId(), card.getPicturePath(),
new Date(), new Date());
try {
pm.makePersistent(c);
} catch(Exception e) {
logger.severe("Create failed: " + e.getMessage());
return null;
} finally {
pm.close();
}
return c;
}
}
Is your Card class using #XmlRootElement and #XmlElement annotations to enable JAXB mapping JSON to/from POJO?
See example:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Book {
#XmlElement(name = "id")
String id;
//...
I am not sure that it is correct to call the annotated web-service method just like a simple method with params. Try to remove all annotations from your CardResource class and invoke this method simply like a class method.

hibernate many-to-many table mapping with extra fields as a list - Java classes?

I am quite interested in a Hibernate mapping such as the Order/Product/LineItem described here:
http://docs.jboss.org/hibernate/stable/core/reference/en/html/example-mappings.html#example-mappings-customerorderproduct
The documentation seems quite thorough, but I am a bit unclear on the semantics of the Java classes that one would create...
Any hints much appreciated.
Thank you!
Misha
Using that example, you would have classes that looked like the following:
import java.util.HashSet;
import java.util.Set;
public class Customer {
private String name = null;
private Set<Order> orders = new HashSet<Order>();
private long id = 0;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Order {
private long id = 0;
private Date date = null;
private Customer customer = null;
private List<LineItem> lineItems = new ArrayList<LineItem>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<LineItem> getLineItems() {
return lineItems;
}
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
}
public class LineItem {
private int quantity = 0;
private Product product = null;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
public class Product {
private long id = 0;
private String serialNumber = null;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
}
If you create the tables as per the structure in the example, that should set you up.
They show the UML and the class members in the diagram.
A Customer can have zero to many Order objects (Set).
An Order has at least one to many LineItem objects. {List).
A LineItem entry corresponds to a Product. So LineItem has exactly one Product object.
Not sure what your question is?

Categories

Resources