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();
Related
I am working with hibernate currently to try and map to and from SQL.
Every time I try to run my code I get the error:
org.hibernate.AnnotationException: mappedBy reference an unknown
target entity property: Catalog.primaryKey.suppliers in
Suppliers.catalogSet There is an error:java.lang.NullPointerException
I have triple checked to make sure I am mapping everything correctly, but I have to be missing something. Does anyone know why I would be getting a null pointer with my given code? These are my class codes:
import javax.persistence.*;
#Entity
#Table(name = "catalog")
#AssociationOverrides({
#AssociationOverride(name = "primaryKey.suppliers",
joinColumns = #JoinColumn(name = "sid")),
#AssociationOverride(name = "primaryKey.parts",
joinColumns = #JoinColumn(name = "pid"))
})
public class Catalog {
//Composite ID
private CatalogId primaryKey = new CatalogId();
//Additional Column
private String cost;
#EmbeddedId
public CatalogId getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(CatalogId primaryKey) {
this.primaryKey = primaryKey;
}
#Transient
public Suppliers getSuppliers(){
return getPrimaryKey().getSupplier();
}
public void setSuppliers(Suppliers supplier){
getPrimaryKey().setSupplier(supplier);
}
#Transient
public Parts getParts(){
return getPrimaryKey().getParts();
}
public void setParts(Parts part){
getPrimaryKey().setParts(part);
}
#Column(name = "cost")
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
}
import java.io.Serializable;
import javax.persistence.*;
#Embeddable
public class CatalogId implements Serializable{
private Suppliers suppliers;
private Parts parts;
#ManyToOne (cascade = CascadeType.ALL)
public Suppliers getSupplier() {
return suppliers;
}
public void setSupplier(Suppliers suppliers) {
this.suppliers = suppliers;
}
#ManyToOne(cascade = CascadeType.ALL)
public Parts getParts() {
return parts;
}
public void setParts(Parts parts) {
this.parts = parts;
}
}
import java.util.*;
import javax.persistence.*;
#Entity
#Table(name = "suppliers")
public class Suppliers {
private long sid;
private String sname;
private String address;
private Set<Catalog> catalogSet = new HashSet<Catalog>();
public Suppliers(String sname, String address) {
this.sname = sname;
this.address = address;
}
public Suppliers() {
}
#Id
#GeneratedValue
#Column(name = "sid")
public long getSid() {
return this.sid;
}
public void setSid(long sid) {
this.sid = sid;
}
#Column(name= "sname")
public String getSname() {
return this.sname;
}
public void setSname(String sname) {
this.sname = sname;
}
#Column(name = "address")
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#OneToMany(mappedBy = "primaryKey.suppliers", cascade = CascadeType.ALL)
public Set<Catalog> getCatalogSet() {
return catalogSet;
}
public void setCatalogSet(Set<Catalog> catalogSet) {
this.catalogSet = catalogSet;
}
public void addRecipe(Catalog catalog){
this.catalogSet.add(catalog);
}
}
import java.util.*;
import javax.persistence.*;
#Entity
#Table(name = "parts")
public class Parts {
private long pid;
private String pname;
private String color;
private Set<Catalog> catalogSet = new HashSet<Catalog>();
public Parts(String pname, String color) {
super();
this.pname = pname;
this.color = color;
}
public Parts() {
super();
}
#Id
#GeneratedValue
#Column(name = "pid")
public long getPid() {
return pid;
}
public void setPid(long pid) {
this.pid = pid;
}
#Column(name = "pname")
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
#Column(name = "color")
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
#OneToMany(mappedBy = "primaryKey.parts", cascade = CascadeType.ALL)
public Set<Catalog> getCatalogSet() {
return this.catalogSet;
}
public void setCatalogSet(Set<Catalog> catalogSet) {
this.catalogSet = catalogSet;
}
public void addCatalog(Catalog catalog){
this.catalogSet.add(catalog);
}
}
This is my (unfinished query code):
import org.hibernate.*;
import org.hibernate.boot.*;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.swing.*;
public class HibernateHql
{
public static void main(String[] args)
{
HibernateSession hibernateSession = new HibernateSession();
SessionFactory sessionFactory;
Session session;
String option = "";
String instruction = "Enter a: Return distinct sids and snames of suppliers who supply a red part or a green part." + "\n" +
"Enter b: Return distinct pids, pnames, and the maximum cost of that part amoung all suppliers that offer the part and that maximum cost is less than 70." + "\n" +
"Enter c: Insert a new catalog row given the supplier id, the part id, and the cost fromthe user of your program." + "\n" +
"Enter d: Quit Program";
try
{
while(true)
{
option = JOptionPane.showInputDialog(instruction);
hibernateSession.setUp();
sessionFactory = hibernateSession.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
if(option.equals("a"))
{
List results = session.createQuery("select distinct c from Parts p join p.catalogSet c where p.color = :color1 or p.color = :color2").setParameter("color1", "red").setParameter("color2", "green").getResultList();
String toShow = "These are suppliers who supply a red or green part:\n";
for(int i=0;i<results.size();i++)
{
Suppliers theSupplier = (Suppliers)((Catalog)results.get(i)).getSuppliers();
toShow += (i+1) + ") " + theSupplier.getSname() + "\n";
}
JOptionPane.showMessageDialog(null, toShow);
}
else if(option.equals("b"))
{
List results = session.createQuery("select max(r.cost)from Suppliers s inner join s.catalogSet r group by f").getResultList();
String toShow = "These are all parts:\n";
for(int i=0;i<results.size();i++)
{
Parts thePart = (Parts)((Catalog)results.get(i)).getParts();
String cost = ((Catalog)results.get(i)).getCost();
if(Integer.parseInt(cost) <= 70){
toShow += (i+1) + ") " + thePart.getPname() + " " + cost;
}
}
JOptionPane.showMessageDialog(null, toShow);
}
else if(option.equals("c"))
{
String allSuppliers = "SID" + "....." + "SNAME" + "\n";
List allS = session.createQuery("from Suppliers").getResultList();
for(int i=0;i<allS.size();i++)
{
Suppliers theSupplier = (Suppliers)allS.get(i);
allSuppliers += theSupplier.getSid() + "....." + theSupplier.getSname() + "\n";
}
JOptionPane.showMessageDialog(null, allSuppliers);
String supplierID = JOptionPane.showInputDialog("Enter Supplier ID: ");
String allParts = "PID" + "....." + "PNAME" + "\n";
List allP = session.createQuery("from Parts p where p.color = :color").setParameter("color", "blue").getResultList();
for(int i=0;i<allS.size();i++)
{
Parts theParts = (Parts)allP.get(i);
allParts += theParts.getPid() + "....." + theParts.getPname() + "\n";
}
JOptionPane.showMessageDialog(null, allParts);
String partsID = JOptionPane.showInputDialog("Enter Parts ID: ");
// List results = session.createQuery("select f1 from Food f1 where f1 not in (select distinct r.primaryKey.food from Ingredient i inner join i.recipeSet r where i.iname = :iname)").setParameter("iname", "Green Onion").getResultList();
// String toShow = "These foods don't have green onion:\n";
// for(int i=0;i<results.size();i++)
// {
// Food theFood = (Food)results.get(i);
// toShow += (i+1) + ") " + theFood.getFname() + "\n";
// }
// JOptionPane.showMessageDialog(null, toShow);
}
else
{
break;
}
session.getTransaction().commit();
session.close();
}
JOptionPane.showMessageDialog(null, "Good Bye");
}
catch(Exception e)
{
System.out.println("There is an error:");
System.out.println(e.toString());
}
}
}
Thank you in advance for your help!
In Suppliers class you have mapped the catalogSet as below:
#OneToMany(mappedBy = "primaryKey.suppliers", cascade = CascadeType.ALL)
public Set<Catalog> getCatalogSet() {
return catalogSet;
}
I do not find any field in Suppliers class called primaryKey. I think you should use sid here to map the relationship between catalogSet and Suppliers class.
Please let me know if I misunderstood your question.
I am developping a java/jee application in which i am using spring boot and hibernate as frameworks i used hibernate search for full text searching but unfortunately i always got an empty list as result.I am using hibernate version 5.1 and hibernate search orm version 5.5.3.Final.Here is my code :
public void search() {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(this.em);
try {
fullTextEntityManager.createIndexer().startAndWait();
// create native Lucene query unsing the query DSL
// alternatively you can write the Lucene query using the Lucene
// query parser
// or the Lucene programmatic API. The Hibernate Search DSL is
// recommended though
QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder()
.forEntity(Application.class)
.get();
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().wildcard().onField("reference").matching("di*")
.createQuery();
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery,
Application.class);
// execute search
List<Application> result = jpaQuery.getResultList();
System.out.println("your result list is "+result);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and here is my entity
package biz.picosoft.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
#Entity
#Indexed
#Table(name = "application",uniqueConstraints = {#UniqueConstraint(columnNames = "reference")})
public class Application implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "reference")
private String reference;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "creationDate")
private Date creationDate;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "status")
private String status;
#Field(index = Index.YES, analyze = Analyze.NO,store = Store.YES)
#Column(name = "deadLine")
private Date deadLine;
#Field(index = Index.YES, analyze = Analyze.NO,store = Store.YES)
#Column(name = "appType")
private String appType;
#Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES)
#Column(name = "projectId")
private Long projectId;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "App_files", joinColumns = { #JoinColumn(name = "idApp") }, inverseJoinColumns = {
#JoinColumn(name = "idFile") })
private List<FileMetadata> listePiecesJointes = new ArrayList<FileMetadata>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDeadLine() {
return deadLine;
}
public void setDeadLine(Date deadLine) {
this.deadLine = deadLine;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public Application() {
super();
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public List<FileMetadata> getListePiecesJointes() {
return listePiecesJointes;
}
public void setListePiecesJointes(List<FileMetadata> listePiecesJointes) {
this.listePiecesJointes = listePiecesJointes;
}
public Application(String reference, Date creationDate, String status, Date deadLine, String appType,Long projectId) {
super();
this.reference = reference;
this.creationDate = creationDate;
this.status = status;
this.deadLine = deadLine;
this.appType = appType;
this.projectId=projectId;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((appType == null) ? 0 : appType.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((deadLine == null) ? 0 : deadLine.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((projectId == null) ? 0 : projectId.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Application other = (Application) obj;
if (appType == null) {
if (other.appType != null)
return false;
} else if (!appType.equals(other.appType))
return false;
if (creationDate == null) {
if (other.creationDate != null)
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
if (deadLine == null) {
if (other.deadLine != null)
return false;
} else if (!deadLine.equals(other.deadLine))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (projectId == null) {
if (other.projectId != null)
return false;
} else if (!projectId.equals(other.projectId))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
#Override
public String toString() {
return "Application [id=" + id + ", reference=" + reference + ", creationDate=" + creationDate + ", status="
+ status + ", deadLine=" + deadLine + ", appType=" + appType + ", projectId=" + projectId + "]";
}
}
I have solved my problem.It was because of subclasses which were not indexed.
Did you make sure your entities are indexed before searching?
If you are using a pre-existing database, or if you initialized your database without using Hibernate ORM APIs (by using SQL directly, or by restoring a dump), your entities are probably not indexed yet.
You should have a look at the mass indexer, which makes it easy to index a lot of entities: https://docs.jboss.org/hibernate/search/5.5/reference/en-US/html_single/#search-batchindex-massindexer
Well, first, sorry for my bad english.
I'm having a problem when generating a webservice.
I have my lib model, which contains the classes Endereco, Cidade e Cliente, and my DAO lib, which contains the database access classes for these models.
In Endereco.java class I have a private attribute Cidade cidade.
I have gotten a webservice to be a control between front end and back end.
The problem is that when I generate this webservice class "address" gets the int attribute city and not the attribute of my base class "Cidade".
Follow the codes of classes:
"ENDERECO.java":
package lib.modelo;
public class Endereco {
private int id;
private Cliente cliente;
private String endereco;
private String numero;
private String complemento;
private Cidade cidade;
private String bairro;
private String uf;
private String cep;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
public Cidade getCidade() {
return cidade;
}
public void setCidade(Cidade cidade) {
this.cidade = cidade;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
}
"CIDADE.java":
package lib.modelo;
public class Cidade {
private int id;
private String descricao;
private double valor_taxa;
public double getValor_taxa() {
return valor_taxa;
}
public void setValor_taxa(double valor_taxa) {
this.valor_taxa = valor_taxa;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
"ENDERECODAO.java":
package lib.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lib.banco.ConexaoBanco;
import lib.modelo.Endereco;
public class EnderecoDAO {
private static final String CONSULTA_POR_ID = "SELECT * FROM cadastros.cliente_endereco WHERE id = ?;";
private static final String CONSULTA_POR_CLIENTE = "SELECT * FROM cadastros.cliente_endereco WHERE fK_cliente = ?;";
private static final String INSERE = "INSERT INTO cadastros.cliente_endereco ( fk_cliente , endereco , numero , complemento , fk_cidade , bairro , uf , cep) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? );";
private static final String ALTERA = "UPDATE cadastros.cliente_endereco SET endereco = ?, numero = ?, complemento = ?, fk_cidade = ?, bairro = ?, uf = ?, cep = ? WHERE fk_cliente = ? AND id = ?;";
public List<Endereco> ConsultarEnderecoPorCliente (int codCliente) throws SQLException{
Connection conexaoSQL = null;
ResultSet rsEndereco = null;
List<Endereco> listaEndereco = new ArrayList<Endereco>();
ClienteDAO clienteDAO = new ClienteDAO();
CidadeDAO cidadeDAO = new CidadeDAO();
try{
conexaoSQL = ConexaoBanco.getConexao("selecao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(CONSULTA_POR_CLIENTE);
pstmt.setInt(1, codCliente);
rsEndereco = pstmt.executeQuery();
while (rsEndereco.next()){
Endereco endereco = new Endereco();
endereco.setId(rsEndereco.getInt("id"));
endereco.setCliente(clienteDAO.CousultaPorId(rsEndereco.getInt("fk_cliente")));
endereco.setEndereco(rsEndereco.getString("endereco"));
endereco.setNumero(rsEndereco.getString("numero"));
endereco.setComplemento(rsEndereco.getString("complemento"));
endereco.setCidade(cidadeDAO.consultaPorId(rsEndereco.getInt("fk_cidade")));
endereco.setBairro(rsEndereco.getString("bairro"));
endereco.setUf(rsEndereco.getString("uf"));
endereco.setCep(rsEndereco.getString("cep"));
listaEndereco.add(endereco);
}
rsEndereco.close();
conexaoSQL.close();
}catch(Exception e){
conexaoSQL.close();
throw new RuntimeException(e);
}
return listaEndereco;
}
public boolean CadastrarEndereco (Endereco endereco) throws SQLException{
boolean status = false;
Connection conexaoSQL = null;
try {
conexaoSQL = ConexaoBanco.getConexao("insercao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(INSERE);
pstmt.setInt(1, endereco.getCliente().getId());
pstmt.setString(2, endereco.getEndereco());
pstmt.setString(3, endereco.getNumero());
pstmt.setString(4, endereco.getComplemento());
pstmt.setInt(5, endereco.getCidade().getId());
pstmt.setString(6, endereco.getBairro());
pstmt.setString(7, endereco.getUf());
pstmt.setString(8, endereco.getCep());
pstmt.execute();
conexaoSQL.close();
status = true;
} catch (Exception e) {
conexaoSQL.close();
throw new RuntimeException(e);
}
return status;
}
public boolean AlterarEndereco (Endereco endereco) throws SQLException{
boolean status = false;
Connection conexaoSQL = null;
try {
conexaoSQL = ConexaoBanco.getConexao("alteracao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(ALTERA);
pstmt.setString(1, endereco.getEndereco());
pstmt.setString(2, endereco.getNumero());
pstmt.setString(3, endereco.getComplemento());
pstmt.setInt(4, endereco.getCidade().getId());
pstmt.setString(5, endereco.getBairro());
pstmt.setString(6, endereco.getUf());
pstmt.setString(7, endereco.getCep());
pstmt.setInt(8, endereco.getCliente().getId());
pstmt.setInt(9, endereco.getId());
pstmt.execute();
conexaoSQL.close();
pstmt.close();
status = true;
} catch (Exception e) {
conexaoSQL.close();
throw new RuntimeException(e);
}
return status;
}
public Endereco ConsultarEnderecoPorId (int codEndereco) throws SQLException{
Connection conexaoSQL = null;
ResultSet rsEndereco = null;
Endereco endereco = new Endereco();
CidadeDAO cidadeDAO = new CidadeDAO();
ClienteDAO clienteDAO = new ClienteDAO();
try {
conexaoSQL = ConexaoBanco.getConexao("selecao");
PreparedStatement pstmt = conexaoSQL.prepareStatement(CONSULTA_POR_ID);
pstmt.setInt(1, codEndereco);
rsEndereco = pstmt.executeQuery();
if(rsEndereco.next()){
endereco.setBairro(rsEndereco.getString("bairro"));
endereco.setCep(rsEndereco.getString("cep"));
endereco.setCidade(cidadeDAO.consultaPorId(rsEndereco.getInt("fk_cidade")));
endereco.setCliente(clienteDAO.CousultaPorId(rsEndereco.getInt("fk_cliente")));
endereco.setComplemento(rsEndereco.getString("complemento"));
endereco.setEndereco(rsEndereco.getString("endereco"));
endereco.setId(rsEndereco.getInt("id"));
endereco.setNumero(rsEndereco.getString("numero"));
endereco.setUf(rsEndereco.getString("uf"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
conexaoSQL.close();
rsEndereco.close();
return endereco;
}
}
And the WebService for ENDERECO "SERVICOENDERECO.java":
package lib.webservice.endereco;
import java.util.ArrayList;
import java.util.List;
import lib.dao.EnderecoDAO;
import lib.modelo.Cidade;
import lib.modelo.Cliente;
import lib.modelo.Endereco;
public class ServicoEndereco {
public Endereco[] consultaPorCliente(int id){
EnderecoDAO eDAO = new EnderecoDAO();
List< Endereco > listaEndereco = new ArrayList<Endereco>();
try{
listaEndereco = eDAO.ConsultarEnderecoPorCliente( id );
}catch(Exception e){
throw new RuntimeException(e);
}
return listaEndereco.toArray( new Endereco[0] );
}
public boolean cadastra( Cliente cliente , String logradouro , String numero ,
String complemento , Cidade cidade , String bairro ,
String uf , String cep){
boolean status = false;
try{
Endereco endereco = new Endereco();
EnderecoDAO eDAO = new EnderecoDAO();
endereco.setCliente(cliente);
endereco.setEndereco(logradouro);
endereco.setNumero(numero);
endereco.setComplemento(complemento);
endereco.setCidade(cidade);
endereco.setBairro(bairro);
endereco.setUf(uf);
endereco.setCep(cep);
status = eDAO.CadastrarEndereco(endereco);
}catch(Exception e){
throw new RuntimeException(e);
}
return status;
}
public boolean altera(Cliente cliente , String logradouro , String numero ,
String complemento , Cidade cidade , String bairro ,
String uf , String cep , int id){
boolean status = false;
try{
Endereco endereco = new Endereco();
EnderecoDAO eDAO = new EnderecoDAO();
endereco.setCliente(cliente);
endereco.setEndereco(logradouro);
endereco.setNumero(numero);
endereco.setComplemento(complemento);
endereco.setCidade(cidade);
endereco.setBairro(bairro);
endereco.setUf(uf);
endereco.setCep(cep);
endereco.setId(id);
status = eDAO.AlterarEndereco(endereco);
}catch(Exception e){
throw new RuntimeException(e);
}
return status;
}
public Endereco consultaPorId (int id){
EnderecoDAO eDAO = new EnderecoDAO();
Endereco endereco = new Endereco();
try {
endereco = eDAO.ConsultarEnderecoPorId(id);
} catch (Exception e) {
throw new RuntimeException(e);
}
return endereco;
}
}
Problem solved!
The difference between the classes was taking place due to my server configuration. When I updated the .jar files from the apache server classpath the code was generated properly.
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.
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.