I'm an amateur programmer and I'm having trouble with the java eclipse persistence named queries. I have an entity class. In this class I have created named queries. With the ClientInformation.getList I have two parameters. One on active (Boolean) and one on type (int). When I remove either one it works like a charm, but when I try them both it transforms the boolean value to an integer.
Entity class
package datamodel;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "CLIENT_INFORMATION")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "ClientInformation.getList", query =
"SELECT c.ciName FROM ClientInformation c WHERE "
+ "(c.ciActive = true or c.ciActive = :ciActive) AND "
+ "(:ciType = 0 OR c.ciType = :ciType)"),
#NamedQuery(name = "ClientInformation.getID", query = "SELECT c.ciId FROM ClientInformation c WHERE c.ciName like :ciName"),
#NamedQuery(name = "ClientInformation.findAll", query = "SELECT c FROM ClientInformation c"),
#NamedQuery(name = "ClientInformation.findByCiId", query = "SELECT c FROM ClientInformation c WHERE c.ciId = :ciId"),
#NamedQuery(name = "ClientInformation.findByCiType", query = "SELECT c FROM ClientInformation c WHERE c.ciType = :ciType")})
public class ClientInformation implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "CI_ID")
private Integer ciId;
#Lob
#Column(name = "CI_NAME", unique=true)
private String ciName;
#Lob
#Column(name = "CI_ADDRESS")
private String ciAddress;
#Lob
#Column(name = "CI_AREACODE")
private String ciAreacode;
#Lob
#Column(name = "CI_CITY")
private String ciCity;
#Lob
#Column(name = "CI_PHONE")
private String ciPhone;
#Lob
#Column(name = "CI_PHONE2")
private String ciPhone2;
#Lob
#Column(name = "CI_EMAIL")
private String ciEmail;
#Column(name = "CI_ACTIVE")
private Boolean ciActive;
#Lob
#Column(name = "CI_NOTE")
private String ciNote;
#Column(name = "CI_TYPE")
private Integer ciType;
public ClientInformation() {
}
public ClientInformation(Integer ciId) {
this.ciId = ciId;
}
public Integer getCiId() {
return ciId;
}
public void setCiId(Integer ciId) {
this.ciId = ciId;
}
public String getCiName() {
return ciName;
}
public void setCiName(String ciName) {
this.ciName = ciName;
}
public String getCiAddress() {
return ciAddress;
}
public void setCiAddress(String ciAddress) {
this.ciAddress = ciAddress;
}
public String getCiAreacode() {
return ciAreacode;
}
public void setCiAreacode(String ciAreacode) {
this.ciAreacode = ciAreacode;
}
public String getCiCity() {
return ciCity;
}
public void setCiCity(String ciCity) {
this.ciCity = ciCity;
}
public String getCiPhone() {
return ciPhone;
}
public void setCiPhone(String ciPhone) {
this.ciPhone = ciPhone;
}
public String getCiPhone2() {
return ciPhone2;
}
public void setCiPhone2(String ciPhone2) {
this.ciPhone2 = ciPhone2;
}
public String getCiEmail() {
return ciEmail;
}
public void setCiEmail(String ciEmail) {
this.ciEmail = ciEmail;
}
public Boolean getCiActive() {
return ciActive;
}
public void setCiActive(Boolean ciActive) {
this.ciActive = ciActive;
}
public String getCiNote() {
return ciNote;
}
public void setCiNote(String ciNote) {
this.ciNote = ciNote;
}
public Integer getCiType() {
return ciType;
}
public void setCiType(Integer ciType) {
this.ciType = ciType;
}
#Override
public int hashCode() {
int hash = 0;
hash += (ciId != null ? ciId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ClientInformation)) {
return false;
}
ClientInformation other = (ClientInformation) object;
if ((this.ciId == null && other.ciId != null) || (this.ciId != null && !this.ciId.equals(other.ciId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "manager.ClientInformation[ ciId=" + ciId + " ]";
}
}
Code snip where I call the named query.
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ManagerPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
List clientList = em.createNamedQuery("ClientInformation.getList")
.setParameter("ciActive", this.inactiveClientSelected)
.setParameter("ciType", this.typeClientSelected)
.getResultList();
clientList_ComboBox.addItem("Kies klant...");
if (clientList.isEmpty() == false) {
for (Object clientList1 : clientList) {
clientList_ComboBox.addItem(clientList1);
}
}
em.close();
emf.close();
This is the message I'm getting.
Call: SELECT CI_NAME FROM CLIENT_INFORMATION WHERE (((CI_ACTIVE = 1)
OR (CI_ACTIVE = 1)) AND ((0 = 0) OR (CI_TYPE = 0))) Internal
Exception: java.sql.SQLSyntaxErrorException: Comparisons between
'BOOLEAN' and 'INTEGER' are not supported. Types must be comparable.
String types must also have matching collation. If collation does not
match, a possible solution is to cast operands to force them to the
default collation (e.g. SELECT tablename FROM sys.systables WHERE
CAST(tablename AS VARCHAR(128)) = 'T1') Query:
ReportQuery(name="ClientInformation.getList"
referenceClass=ClientInformation sql="SELECT CI_NAME FROM
CLIENT_INFORMATION WHERE (((CI_ACTIVE = ?) OR (CI_ACTIVE = ?)) AND ((?
= ?) OR (CI_TYPE = ?)))") Error Code: 30000 Call: SELECT CI_NAME FROM CLIENT_INFORMATION WHERE (((CI_ACTIVE = 1) OR (CI_ACTIVE = 1)) AND ((0
= 0) OR (CI_TYPE = 0))) Query: ReportQuery(name="ClientInformation.getList"
referenceClass=ClientInformation sql="SELECT CI_NAME FROM
CLIENT_INFORMATION WHERE (((CI_ACTIVE = ?) OR (CI_ACTIVE = ?)) AND ((?
= ?) OR (CI_TYPE = ?)))")
Any suggestions or do I need to give more information?
Edit: When I remove the last part from the query ("... AND (:ciType = ...etc) the query works fine, so I think I ruled out the actual parameter passing/ the code passes a boolean. Also, when I remove the first parameter (the Boolean) it works as well. So It's (the combination of) the two parameters.
Related
I have a JTable that displays data from mysql, the code below is works (can insert, update, delete) But if I delete a row and create another with the same id, the previous data in the row (before I delete it) appears instead of new data.
code for insert and delete
private void simpanBtnActionPerformed(java.awt.event.ActionEvent evt) {
String hantaranID = hantaranIDText.getText();
String namaLengkap = namaLengkapET.getText();
String alamat = jTextArea1.getText();
String hp = noHp.getText();
Date pengambilan = jXDatePicker1.getDate();
Date pengembalian = jXDatePicker2.getDate();
if (hantaranID.isEmpty()){
JOptionPane.showMessageDialog(null, "Hantaran ID tidak boleh kosong.");
} else if (namaLengkap.isEmpty()){
JOptionPane.showMessageDialog(null, "Nama lengkap tidak boleh kosong.");
} else if (alamat.isEmpty()) {
JOptionPane.showMessageDialog(null, "Alamat tidak boleh kosong.");
} else if (hp.isEmpty()){
JOptionPane.showMessageDialog(null, "Nomor Hand Phone tidak boleh kosong.");
} else if (pengambilan != null && pengembalian != null){
try {
DateFormat sysDate = new SimpleDateFormat("yyyy/MM/dd");
String tglPengambilan = sysDate.format(jXDatePicker1.getDate()).toString();
String tglPengembalian = sysDate.format(jXDatePicker2.getDate()).toString();
Connection conn = MyDBConnection.getConnection();
String insert = "insert into hantaran (hantaran_id, nama_lengkap, alamat, no_hp, tgl_pengambilan, tgl_pengembalian)"
+ "values (?, ?, ? , ? , ?, ?)";
PreparedStatement insertHantaran = conn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
insertHantaran.setString(1, hantaranID);
insertHantaran.setString(2, namaLengkap);
insertHantaran.setString(3, alamat);
insertHantaran.setString(4, hp);
insertHantaran.setString(5, tglPengambilan);
insertHantaran.setString(6, tglPengembalian);
insertHantaran.executeUpdate();
hantaranTabel.revalidate();
hantaranList.clear();
hantaranList.addAll( hantaranQuery.getResultList());
hantaranIDText.setText("");
namaLengkapET.setText("");
jTextArea1.setText("");
noHp.setText("");
jXDatePicker1.setDate(null);
jXDatePicker2.setDate(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Tanggal Pengambilan dan Pengembalian tidak boleh kosong.");
}
// TODO add your handling code here:
}
private void hapusBtnActionPerformed(java.awt.event.ActionEvent evt) {
String id = hantaranIDText.getText();
Object[] options = { "YA", "Tidak" };
int choice = JOptionPane.showOptionDialog(null,
"Hapus data ini??",
"Hapus..!",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (choice == JOptionPane.YES_OPTION){
try {
Connection conn = MyDBConnection.getConnection();
String reqq = "DELETE FROM hantaran WHERE hantaran_id = ?";
PreparedStatement delete = conn.prepareStatement(reqq);
delete.setString(1, id);
delete.executeUpdate();
hantaranTabel.revalidate();
hantaranList.clear();
hantaranList.addAll( hantaranQuery.getResultList());
editBtn.setText("EDIT");
hantaranIDText.setText("");
namaLengkapET.setText("");
jTextArea1.setText("");
noHp.setText("");
jXDatePicker1.setDate(null);
jXDatePicker2.setDate(null);
hapusBtn.setEnabled(false);
simpanBtn.setEnabled(true);
} catch (Exception ex) {
Logger.getLogger(HennaPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
my class
package aplikasi_mahar;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
/**
*
* #author User
*/
#Entity
#Table(name = "hantaran", catalog = "mahardb", schema = "")
#NamedQueries({
#NamedQuery(name = "Hantaran.findAll", query = "SELECT h FROM Hantaran h"),
#NamedQuery(name = "Hantaran.findByHantaranId", query = "SELECT h FROM Hantaran h WHERE h.hantaranId = :hantaranId"),
#NamedQuery(name = "Hantaran.findByNamaLengkap", query = "SELECT h FROM Hantaran h WHERE h.namaLengkap = :namaLengkap"),
#NamedQuery(name = "Hantaran.findByAlamat", query = "SELECT h FROM Hantaran h WHERE h.alamat = :alamat"),
#NamedQuery(name = "Hantaran.findByNoHp", query = "SELECT h FROM Hantaran h WHERE h.noHp = :noHp"),
#NamedQuery(name = "Hantaran.findByTglPengambilan", query = "SELECT h FROM Hantaran h WHERE h.tglPengambilan = :tglPengambilan"),
#NamedQuery(name = "Hantaran.findByTglPengembalian", query = "SELECT h FROM Hantaran h WHERE h.tglPengembalian = :tglPengembalian")})
public class Hantaran implements Serializable {
#Transient
private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "hantaran_id")
private Integer hantaranId;
#Basic(optional = false)
#Column(name = "nama_lengkap")
private String namaLengkap;
#Basic(optional = false)
#Column(name = "alamat")
private String alamat;
#Basic(optional = false)
#Column(name = "no_hp")
private String noHp;
#Basic(optional = false)
#Column(name = "tgl_pengambilan")
#Temporal(TemporalType.DATE)
private Date tglPengambilan;
#Basic(optional = false)
#Column(name = "tgl_pengembalian")
#Temporal(TemporalType.DATE)
private Date tglPengembalian;
public Hantaran() {
}
public Hantaran(Integer hantaranId) {
this.hantaranId = hantaranId;
}
public Hantaran(Integer hantaranId, String namaLengkap, String alamat, String noHp, Date tglPengambilan, Date tglPengembalian) {
this.hantaranId = hantaranId;
this.namaLengkap = namaLengkap;
this.alamat = alamat;
this.noHp = noHp;
this.tglPengambilan = tglPengambilan;
this.tglPengembalian = tglPengembalian;
}
public Integer getHantaranId() {
return hantaranId;
}
public void setHantaranId(Integer hantaranId) {
Integer oldHantaranId = this.hantaranId;
this.hantaranId = hantaranId;
changeSupport.firePropertyChange("hantaranId", oldHantaranId, hantaranId);
}
public String getNamaLengkap() {
return namaLengkap;
}
public void setNamaLengkap(String namaLengkap) {
String oldNamaLengkap = this.namaLengkap;
this.namaLengkap = namaLengkap;
changeSupport.firePropertyChange("namaLengkap", oldNamaLengkap, namaLengkap);
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
String oldAlamat = this.alamat;
this.alamat = alamat;
changeSupport.firePropertyChange("alamat", oldAlamat, alamat);
}
public String getNoHp() {
return noHp;
}
public void setNoHp(String noHp) {
String oldNoHp = this.noHp;
this.noHp = noHp;
changeSupport.firePropertyChange("noHp", oldNoHp, noHp);
}
public Date getTglPengambilan() {
return tglPengambilan;
}
public void setTglPengambilan(Date tglPengambilan) {
Date oldTglPengambilan = this.tglPengambilan;
this.tglPengambilan = tglPengambilan;
changeSupport.firePropertyChange("tglPengambilan", oldTglPengambilan, tglPengambilan);
}
public Date getTglPengembalian() {
return tglPengembalian;
}
public void setTglPengembalian(Date tglPengembalian) {
Date oldTglPengembalian = this.tglPengembalian;
this.tglPengembalian = tglPengembalian;
changeSupport.firePropertyChange("tglPengembalian", oldTglPengembalian, tglPengembalian);
}
#Override
public int hashCode() {
int hash = 0;
hash += (hantaranId != null ? hantaranId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Hantaran)) {
return false;
}
Hantaran other = (Hantaran) object;
if ((this.hantaranId == null && other.hantaranId != null) || (this.hantaranId != null && !this.hantaranId.equals(other.hantaranId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "aplikasi_mahar.Hantaran[ hantaranId=" + hantaranId + " ]";
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
changeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
changeSupport.removePropertyChangeListener(listener);
}
}
connection class
public class MyDBConnection {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mahardb", "root", "");
}
return connection;
}
}
Notes : i'm using persistent connection, java jdk7
You have to set new Data for your TableModel or remove deleted Data/Row from TableModel and call fireTableDataChanged method:
yourTableModel.setData(getYourData());
yourTableModel.fireTableDataChanged();
i'm creating a java EE (web) application using JPA and EJB for model-tier.
i think i have to use Session Beans for CRUD.
this is my BrandFacade.java (session bean)
package model.business;
import model.localinterface.BrandFacadeLocal;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.entities.Brand;
#Stateless
public class BrandFacade extends AbstractFacade<Brand> implements BrandFacadeLocal, BrandFacadeRemote {
#PersistenceContext(unitName = "MyWheelEE-ejbPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public BrandFacade() {
super(Brand.class);
}
#Override
public boolean CreateBrand(String name) {
Brand brand=new Brand(0, name);
boolean result=true;
try {
em.persist(brand);
} catch (Exception e) {
result=false;
}
em.close();
return result;
}
#Override
public void deleteBrand(int brandOid) {
em.remove(getBrandByOid(brandOid));
em.flush();
}
#Override
public Brand getBrandByOid(int brandOid) {
em.flush();
return em.find(Brand.class, brandOid);
}
#Override
public void editBrand(Brand brand) {
em.merge(brand);
em.flush();
}
}
and this is my Brand.java class (entity)
package model.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "brand")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Brand.findAll", query = "SELECT b FROM Brand b"),
#NamedQuery(name = "Brand.findByOid", query = "SELECT b FROM Brand b WHERE b.oid = :oid"),
#NamedQuery(name = "Brand.findByName", query = "SELECT b FROM Brand b WHERE b.name = :name")})
public class Brand implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "oid")
private Integer oid;
#Basic(optional = false)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "brandOid")
private List<Wheelchair> wheelchairList;
public Brand() {
}
public Brand(Integer oid) {
this.oid = oid;
}
public Brand(Integer oid, String name) {
this.oid = oid;
this.name = name;
}
public Integer getOid() {
return oid;
}
public void setOid(Integer oid) {
this.oid = oid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlTransient
public List<Wheelchair> getWheelchairList() {
return wheelchairList;
}
public void setWheelchairList(List<Wheelchair> wheelchairList) {
this.wheelchairList = wheelchairList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (oid != null ? oid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Brand)) {
return false;
}
Brand other = (Brand) object;
if ((this.oid == null && other.oid != null) || (this.oid != null && !this.oid.equals(other.oid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.entities.Brand[ oid=" + oid + " ]";
}
}
i wish to know how does .merge method work... i think it search in the DB the entity which has the primary key of the entity passed and then it works on edited fields right?
but how i can edit a brand knowing only the name?
It's quite simple really, here your answers:
I wish to know how does .merge method work...
When you call merge method, JPA will verify if the field marked as primary key (#Id) is not null:
- IF YES: JPA will create a new record in your database
- IT NOT: JPA will update your record using the id field value, something like (UPDATE table_name ..... WHERE id=?)
So, you are right :)
but how i can edit a brand knowing only the name?
If you wanna edit a record knowing another field rather than Id field, you will have 2 options:
1. Write JPQL, something like:
UPDATE Person p SET p.lastName = 'New Last Name' WHERE p.name = 'his name'
Write a Native Query, in this case, you will write PLAIN SQL and the run it
In both cases, you will need to do something like:
Query query = em.createQuery or em.createNativeQuery
and then just execute it
I have an issue with how hibernate implemented a many to many relationship.
Hibernate created the 2 following classes to map the tables relationship:
package entities;
// default package
// Generated Jul 13, 2015 2:58:02 PM by Hibernate Tools 4.0.0
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* CategoriesDuSpectacle generated by hbm2java
*/
#Entity
#Table(name = "Categories_Du_Spectacle")
public class CategoriesDuSpectacle implements java.io.Serializable {
private CategoriesDuSpectacleId id;
public CategoriesDuSpectacle() {
}
public CategoriesDuSpectacle(CategoriesDuSpectacleId id) {
this.id = id;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "spectacleId", column = #Column(name = "Spectacle_Id", nullable = false)),
#AttributeOverride(name = "categorieId", column = #Column(name = "Categorie_Id", nullable = false)),
#AttributeOverride(name = "duree", column = #Column(name = "Duree")),
#AttributeOverride(name = "commentaire", column = #Column(name = "Commentaire")),
#AttributeOverride(name = "theme", column = #Column(name = "Theme")),
#AttributeOverride(name = "contrainte", column = #Column(name = "Contrainte")) })
public CategoriesDuSpectacleId getId() {
return this.id;
}
public void setId(CategoriesDuSpectacleId id) {
this.id = id;
}
}
and:
package entities;
// default package
// Generated Jul 13, 2015 2:58:02 PM by Hibernate Tools 4.0.0
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* CategoriesDuSpectacleId generated by hbm2java
*/
#Embeddable
public class CategoriesDuSpectacleId implements java.io.Serializable {
private int spectacleId;
private int categorieId;
private Integer duree;
private String commentaire;
private String theme;
private String contrainte;
public CategoriesDuSpectacleId() {
}
public CategoriesDuSpectacleId(int spectacleId, int categorieId) {
this.spectacleId = spectacleId;
this.categorieId = categorieId;
}
public CategoriesDuSpectacleId(int spectacleId, int categorieId,
Integer duree, String commentaire, String theme, String contrainte) {
this.spectacleId = spectacleId;
this.categorieId = categorieId;
this.duree = duree;
this.commentaire = commentaire;
this.theme = theme;
this.contrainte = contrainte;
}
#Column(name = "Spectacle_Id", nullable = false)
public int getSpectacleId() {
return this.spectacleId;
}
public void setSpectacleId(int spectacleId) {
this.spectacleId = spectacleId;
}
#Column(name = "Categorie_Id", nullable = false)
public int getCategorieId() {
return this.categorieId;
}
public void setCategorieId(int categorieId) {
this.categorieId = categorieId;
}
#Column(name = "Duree")
public Integer getDuree() {
return this.duree;
}
public void setDuree(Integer duree) {
this.duree = duree;
}
#Column(name = "Commentaire")
public String getCommentaire() {
return this.commentaire;
}
public void setCommentaire(String commentaire) {
this.commentaire = commentaire;
}
#Column(name = "Theme")
public String getTheme() {
return this.theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
#Column(name = "Contrainte")
public String getContrainte() {
return this.contrainte;
}
public void setContrainte(String contrainte) {
this.contrainte = contrainte;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof CategoriesDuSpectacleId))
return false;
CategoriesDuSpectacleId castOther = (CategoriesDuSpectacleId) other;
return (this.getSpectacleId() == castOther.getSpectacleId())
&& (this.getCategorieId() == castOther.getCategorieId())
&& ((this.getDuree() == castOther.getDuree()) || (this
.getDuree() != null && castOther.getDuree() != null && this
.getDuree().equals(castOther.getDuree())))
&& ((this.getCommentaire() == castOther.getCommentaire()) || (this
.getCommentaire() != null
&& castOther.getCommentaire() != null && this
.getCommentaire().equals(castOther.getCommentaire())))
&& ((this.getTheme() == castOther.getTheme()) || (this
.getTheme() != null && castOther.getTheme() != null && this
.getTheme().equals(castOther.getTheme())))
&& ((this.getContrainte() == castOther.getContrainte()) || (this
.getContrainte() != null
&& castOther.getContrainte() != null && this
.getContrainte().equals(castOther.getContrainte())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getSpectacleId();
result = 37 * result + this.getCategorieId();
result = 37 * result
+ (getDuree() == null ? 0 : this.getDuree().hashCode());
result = 37
* result
+ (getCommentaire() == null ? 0 : this.getCommentaire()
.hashCode());
result = 37 * result
+ (getTheme() == null ? 0 : this.getTheme().hashCode());
result = 37
* result
+ (getContrainte() == null ? 0 : this.getContrainte()
.hashCode());
return result;
}
}
I apologize for the fields naes in French.
Now, when I try to catch all of the entities:
List l = session.createCriteria(CategoriesDuSpectacle.class).list();
This works fine.
But when I try to add a criteria:
l = session.createCriteria(CategoriesDuSpectacle.class).add(Restrictions.ilike("commentaire", "a")).list();
I get the following error:
org.hibernate.QueryException: could not resolve property: commentaire of: entities.CategoriesDuSpectacle
This sounds strange to me as the concerned field is mentionned in CategoriesDuSpectacle class:
#EmbeddedId
#AttributeOverrides({
{...}
#AttributeOverride(name = "commentaire", column = #Column(name = "Commentaire")),
{...}
})
Any idea about what I missed?
Thx in advance.
a good night made me figure it out.
I used the parameter on the wrong object:
l = session.createCriteria(CategoriesDuSpectacle.class).add(Restrictions.ilike("commentaire", "a")).list();
While it should have been this way:
l = session.createCriteria(CategoriesDuSpectacle.class).add(Restrictions.ilike("id.commentaire", "a")).list();
Hope it will help someone else.
I have two model classes:
Class 1 looks like this:
#Entity
#Table(name = "cdm_location_charge_class", catalog = "emscribedx")
public class Cdm_location_charge_class {
private static Logger LOG = Logger.getLogger(Cdm_location_charge_class.class);
private int indx;
private String location;
private String charge_Class;
private List <Cdm_trans> cdm_Trans;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "indx")
public int getIndx() {
return indx;
}
public void setIndx(int indx) {
this.indx = indx;
}
#Column(name = "location")
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
#Column(name = "charge_Class")
public String getCharge_Class() {
return charge_Class;
}
public void setCharge_Class(String charge_Class) {
this.charge_Class = charge_Class;
}
#OneToMany (mappedBy = "cdm_location_charge_class", targetEntity = Cdm_trans.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Cdm_trans> getCdm_Trans() {
return cdm_Trans;
}
public void setCdm_Trans(List<Cdm_trans> cdm_Trans) {
this.cdm_Trans = cdm_Trans;
}
And class 2 looks like this:
#Entity
#Table(name = "cdm_Trans", catalog = "emscribedx")
public class Cdm_trans {
private static Logger LOG = Logger.getLogger(Cdm_trans.class);
private int indx;
private String charge_Class;
private String charge_Code;
private String charge_Description;
private String charge_Eligibility;
private String exp_Date;
private BigDecimal rate_Charge;
private String cpt_Code;
private int rev_Code;
private String charge_Type;
private Cdm_location_charge_class cdm_location_charge_class;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "indx")
public int getIndx() {
return indx;
}
public void setIndx(int indx) {
this.indx = indx;
}
#Column(name = "charge_Class")
public String getCharge_Class() {
return charge_Class;
}
public void setCharge_Class(String charge_Class) {
this.charge_Class = charge_Class;
}
#Column(name = "charge_Code")
public String getCharge_Code() {
return charge_Code;
}
public void setCharge_Code(String charge_Code) {
this.charge_Code = charge_Code;
}
#Column(name = "charge_Description")
public String getCharge_Description() {
return charge_Description;
}
public void setCharge_Description(String charge_Description) {
this.charge_Description = charge_Description;
}
#Column(name = "charge_Eligibility")
public String getCharge_Eligibility() {
return charge_Eligibility;
}
public void setCharge_Eligibility(String charge_Eligibility) {
this.charge_Eligibility = charge_Eligibility;
}
#Column(name = "exp_Date")
public String getExp_Date() {
return exp_Date;
}
public void setExp_Date(String exp_Date) {
this.exp_Date = exp_Date;
}
#Column(name = "rate_Charge")
public BigDecimal getRate_Charge() {
return rate_Charge;
}
public void setRate_Charge(BigDecimal rate_Charge) {
this.rate_Charge = rate_Charge;
}
#Column(name = "cpt_Code")
public String getCpt_Code() {
return cpt_Code;
}
public void setCpt_Code(String cpt_Code) {
this.cpt_Code = cpt_Code;
}
#Column(name = "rev_Code")
public int getRev_Code() {
return rev_Code;
}
public void setRev_Code(int rev_Code) {
this.rev_Code = rev_Code;
}
#Column(name = "charge_Type")
public String getCharge_Type() {
return charge_Type;
}
public void setCharge_Type(String charge_Type) {
this.charge_Type = charge_Type;
}
#ManyToOne
#JoinColumn(name = "charge_Class", insertable = false, updatable = false)
public Cdm_location_charge_class getCdm_location_charge_class() {
return cdm_location_charge_class;
}
public void setCdm_location_charge_class(
Cdm_location_charge_class cdm_location_charge_class) {
this.cdm_location_charge_class = cdm_location_charge_class;
}
}
The two classes correspond to two underlying tables:
Cdm_trans and Cdm_location_charge_class.
I want to create a Hibernate Service that will give me the same result as the following sql query:
select cdm_trans.* from Cdm_trans, Cdm_location_charge_class where
cdm_location_charge_class.charge_Class = cdm_trans.charge_Class and
cdm_location_charge_class.location = <Some location passed to the method> and
Cdm_trans.charge_Description like '%<Some search term passed into the method>%;
My preference would be to do this using the Hibernate criteria API. But I will go with HQL if that is the only way. Can someone show me how to do this?
I've tried this HQL query:
Query query = session.createQuery("FROM cdm_location_charge_class as cl INNER JOIN cl.cdm_Trans where cl.location = :location and cdm_Trans.charge_Description like :search");
But I I get an error:
cdm_location_charge_class is not mapped
If you want to use Criteria, you just add a restriction.
List cats = session.createCriteria(Cat.class)
.createCriteria("kittens")
.add( Restrictions.like("name", "Iz%") )
.list();
HQL example:
Query query = session.createQuery("FROM Cdm_location_charge_class cl " +
"INNER JOIN cl.cdm_Trans trans " +
"where cl.location = :location and trans.charge_Description like :search")
.setParameter("location", locationValue)
.setParameter("search", "%" + searchValue + "%");
Can you be more specific about the issue, or are you just asking for a very specific tutorial?
Anyway why is HQL second choice. IMHO the Criteria Helper should only be used when constructing dynamic queries (add conditions based on user input for example). If you have a static query i would suggest HQL. It is also supposed to be faster. Also look into NamedQuery.
Here is the documentation on Criteria queries in Hibernate:
http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querycriteria.html
Specifically, you want to look at the Restrictions class (http://docs.jboss.org/hibernate/orm/3.3/api/org/hibernate/criterion/Restrictions.html) and static methods like() and ilike(), where the latter handles case-insensitive comparison. I also tend towards HQL for static queries, but I have seen benefit at times to make static elements configurable, especially for debugging. Therefore, I may use the dynamic query approach with the query stored in a configuration file, so I can alter it easily for testing even though the application runs the same query typically.
Respectfully yours,
Kevin
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I try to update existing data rows in database but i get that exception:
[EL Warning]: 2012-10-24 20:02:27.798--UnitOfWork(22664464)--Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '20-http://www.vilpra.lt/products/Foto/Aremikas/Katilas_zvake_big' for key 'PRIMARY' Error Code: 1062 Call: INSERT INTO x_links_media (image, link_id) VALUES (?, ?) bind => [2 parameters bound] Query: InsertObjectQuery(database.entity.XLinksMedia[ xLinksMediaPK=database.entity.XLinksMediaPK[ linkId=20, image=http://www.link.lt/products.jpg ] ])
The main object class is look like code below. There is some variables with relation OneToMany.
package database.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "x_parser_links")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "XParserLinks.findAll", query = "SELECT x FROM XParserLinks x"),
#NamedQuery(name = "XParserLinks.findByLinkId", query = "SELECT x FROM XParserLinks x WHERE x.linkId = :linkId"),
#NamedQuery(name = "XParserLinks.findByPageId", query = "SELECT x FROM XParserLinks x WHERE x.pageId = :pageId"),
#NamedQuery(name = "XParserLinks.findByLink", query = "SELECT x FROM XParserLinks x WHERE x.link = :link"),
#NamedQuery(name = "XParserLinks.findByLevel", query = "SELECT x FROM XParserLinks x WHERE x.level = :level"),
#NamedQuery(name = "XParserLinks.findByLinkType", query = "SELECT x FROM XParserLinks x WHERE x.linkType = :linkType"),
#NamedQuery(name = "XParserLinks.findByCreateDate", query = "SELECT x FROM XParserLinks x WHERE x.createDate = :createDate"),
#NamedQuery(name = "XParserLinks.findByDelDate", query = "SELECT x FROM XParserLinks x WHERE x.delDate = :delDate")})
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#Column(name = "page_id")
private Integer pageId;
#Column(name = "link")
private String link;
#Column(name = "level")
private Integer level;
#Column(name = "link_type")
private Short linkType;
#Column(name = "create_date")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name = "del_date")
#Temporal(TemporalType.TIMESTAMP)
private Date delDate;
#JoinColumn(name = "tev_link_id")
#OneToOne(cascade = CascadeType.ALL)
private XParserLinks tevas;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksVarchar.class, cascade = CascadeType.ALL)
private List<XLinksVarchar> atributes;
public XParserLinks() {
}
public XParserLinks(Integer linkId) {
this.linkId = linkId;
}
public Integer getLinkId() {
return linkId;
}
public void setLinkId(Integer linkId) {
this.linkId = linkId;
}
public Integer getPageId() {
return pageId;
}
public void setPageId(Integer pageId) {
this.pageId = pageId;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Short getLinkType() {
return linkType;
}
public void setLinkType(Short linkType) {
this.linkType = linkType;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getDelDate() {
return delDate;
}
public void setDelDate(Date delDate) {
this.delDate = delDate;
}
public XParserLinks getTevas() {
return tevas;
}
public void setTevas(XParserLinks tevas) {
this.tevas = tevas;
}
public List<XLinksMedia> getFotos() {
return fotos;
}
public void setFotos(List<XLinksMedia> fotos) {
this.fotos = fotos;
}
public List<XLinksVarchar> getAtributes() {
return atributes;
}
public void setAtributes(List<XLinksVarchar> atributes) {
this.atributes = atributes;
}
#Override
public int hashCode() {
int hash = 0;
hash += (linkId != null ? linkId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof XParserLinks)) {
return false;
}
XParserLinks other = (XParserLinks) object;
if ((this.linkId == null && other.linkId != null) || (this.linkId != null && !this.linkId.equals(other.linkId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "database.entity.XParserLinks[ linkId=" + linkId + " ]";
}
}
And here is code where I want to proceed data. XParserLinks object is the man object like code above. In this example I check if object do not have his primary key LinkId then create new object with persist, but else just update object and his values, but I get exception like I mean before when I want to update existing object.
XParserLinks e = entry.getValue();
if (e.getLinkId() == null) {
try {
TarpineManager.startTransaction();
TarpineManager.persist(e);
TarpineManager.commitTransaction();
} catch (Exception ex) {
ex.printStackTrace();
if (TarpineManager.getInstance().getTransaction().isActive()) {
TarpineManager.rollbackTransaction();
}
}
} else {
try {
TarpineManager.startTransaction();
TarpineManager.commitTransaction();
} catch (Exception ex) {
ex.printStackTrace();
if (TarpineManager.getInstance().getTransaction().isActive()) {
TarpineManager.rollbackTransaction();
}
}
}
Are you, by any chance, creating your entity and setting its Id by force? I see your class has a setLinkId(Integer linkId) method on it.
First of all, you should be using merge instead of persist. Now, whit this in mind, the exception is also being thrown by the merge method because JPA can't define if the entity you want to persist is a new one or it's a previosuly fetched one, because the states in the lifecycle aren't the same.
If you create an object and set its id, that entity has the state new, but if you fetched the entity before it should have a detached state. When merged, a detached entity will be correctly updated but a new entity will be persisted and, since the id is taken, the exception is thrown.
You have the entity's ID, so you better fetch them before, update the object and then merge them.