I'm trying persist a relationship #ManyToMany. I created an association class using #IdClass for association, but doesn't work using persist, works only using merge. I need add others registers but using merge doesn't work because the register is always updated.
I want my table in the database looks like this
id_aluno | id_graduacao | grau | date
1 1 FIRST 2014-08-02
1 1 SECOND 2014-08-02
1 1 THIRD 2014-08-02
Entities
#Entity
#Table(name="aluno")
public class Aluno implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
//informacoes gerais
#NotNull
private String nome;
//historico de graduacao
#OneToMany(mappedBy = "aluno")
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Aluno(){}
/** adiciona lista de HistoricoDeGraduacao para aluno */
public void addListaHistoricoGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
///gets e sets
#Entity
#Table(name="graduacao")
public class Graduacao implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
#NotNull #Column(unique = true)
private String graduacao;
#ElementCollection
#CollectionTable(name="graus_graduacao", joinColumns=#JoinColumn(name="id_graduacao"))
#Column(name="graus")
private List<String> graus;
#OneToMany(mappedBy = "graduacao")
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Graduacao() {
}
/** adiciona historicodegraduacao a graduacao */
public void addHistoricoDeGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
//gets e sets
public class HistoricoDeGraduacaoId implements Serializable {
private static final long serialVersionUID = 1L;
private Aluno aluno;
private Graduacao graduacao;
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Graduacao getGraduacao() {
return graduacao;
}
public void setGraduacao(Graduacao graduacao) {
this.graduacao = graduacao;
}
#Entity
#IdClass(HistoricoDeGraduacaoId.class)
public class HistoricoDeGraduacao implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "id_aluno")
private Aluno aluno;
#Id
#ManyToOne
#JoinColumn(name="id_graduacao")
private Graduacao graduacao;
private String grau;
#Temporal(TemporalType.DATE)
private Date dataGraduou;
public HistoricoDeGraduacao() {
}
//gets e sets
//persisting
public void insert(){
//doesn't work using persist, works only with merge but record is always updated and not added
em.getTransaction().begin();
Aluno a = new Aluno();
a.setId(1); //aluno have Id
Graduacao g = new Graduacao();
g.setId(1); //graduacao have Id
HistoricoDeGraduacao hdg1 = new HistoricoDeGraduacao();
hdg1.setAluno(a);
hdg1.setGraduacao(g);
hdg1.setDataGraduou(new Date());
hdg1.setGrau("FIRST");
a.addHistoricoDeGraduacao(hdg1);
g.addHistoricoDeGraduacao(hdg1);
em.persist(hdg1);
em.getTransaction().commit();
HistoricoDeGraduacao hdg2 = new HistoricoDeGraduacao();
hdg2.setAluno(a);
hdg2.setGraduacao(g);
hdg2.setDataGraduou(new Date());
hdg2.setGrau("SECOND");
a.addHistoricoDeGraduacao(hdg2);
g.addHistoricoDeGraduacao(hdg2);
em.persist(hdg2);
em.getTransaction().commit();
HistoricoDeGraduacao hdg3 = new HistoricoDeGraduacao();
hdg3.setAluno(a);
hdg3.setGraduacao(g);
hdg3.setDataGraduou(new Date());
hdg3.setGrau("THIRD");
a.addHistoricoDeGraduacao(hdg3);
g.addHistoricoDeGraduacao(hdg3);
em.persist(hdg3);
em.getTransaction().commit();
em.close();
}
Using persist doesn't work, using merge works but the record is always updated and not add new records how I need.
Any idea how to I do this ?
after days searching and trying some solution, finally works !
here how I did
#Entity
#Table(name="aluno")
public class Aluno implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
//informacoes gerais
#NotNull
private String nome;
//historico de graduacao
#OneToMany(mappedBy = "aluno", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Aluno() {
}
public void addListaHistoricoGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
public void setListaHistoricoGraduacao(List<HistoricoDeGraduacao> listaHistoricoGraduacao) {
this.listaHistoricoGraduacao = listaHistoricoGraduacao;
}
#Override
public int hashCode() {
int hash = 7;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Aluno other = (Aluno) obj;
return true;
}
}
#Entity
#Table(name="graduacao")
public class Graduacao implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
private Integer id;
#NotNull #Column(unique = true)
private String graduacao;
#ElementCollection
#CollectionTable(name="graus_graduacao", joinColumns=#JoinColumn(name="id_graduacao"))
#Column(name="graus")
private List<String> graus;
#OneToMany(mappedBy = "graduacao", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<HistoricoDeGraduacao> listaHistoricoGraduacao;
public Graduacao() {
}
public Graduacao(Integer id, String graduacao, List<String> graus) {
this.id = id;
this.graduacao = graduacao;
this.graus = graus;
}
/** adiciona historicodegraduacao a graduacao */
public void addHistoricoDeGraduacao(HistoricoDeGraduacao hdg){
if(listaHistoricoGraduacao == null){
listaHistoricoGraduacao = new ArrayList<HistoricoDeGraduacao>();
}
listaHistoricoGraduacao.add(hdg);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGraduacao() {
return graduacao;
}
public void setGraduacao(String graduacao) {
this.graduacao = graduacao;
}
public List<String> getGraus() {
return graus;
}
public void setGraus(List<String> graus) {
this.graus = graus;
}
public List<HistoricoDeGraduacao> getListaHistoricoGraduacao() {
return listaHistoricoGraduacao;
}
public void setListaHistoricoGraduacao(List<HistoricoDeGraduacao> listaHistoricoGraduacao) {
this.listaHistoricoGraduacao = listaHistoricoGraduacao;
}
public String toString(){
return graduacao;
}
}
#Embeddable
public class HistoricoDeGraduacaoId implements Serializable {
private static final long serialVersionUID = 1L;
#JoinColumn(name="EMP_ID")
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj); //To change body of generated methods, choose Tools | Templates.
}
#Override
public int hashCode() {
return super.hashCode(); //To change body of generated methods, choose Tools | Templates.
}
}
#Entity
public class HistoricoDeGraduacao implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
HistoricoDeGraduacaoId pk;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_aluno")
private Aluno aluno;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="id_graduacao")
private Graduacao graduacao;
private String grau;
#Temporal(TemporalType.DATE)
private Date dataGraduou;
public HistoricoDeGraduacao() {
}
public void begin(){
//instancia pk
pk = new HistoricoDeGraduacaoId();
//aqui insiro o id
pk.setId(new HistoricoDeGraduacaoDAO().getIndex());
}
public HistoricoDeGraduacaoId getPk() {
return pk;
}
public void setPk(HistoricoDeGraduacaoId pk) {
this.pk = pk;
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public Graduacao getGraduacao() {
return graduacao;
}
public void setGraduacao(Graduacao graduacao) {
this.graduacao = graduacao;
}
public String getGrau() {
return grau;
}
public void setGrau(String grau) {
this.grau = grau;
}
public Date getDataGraduou() {
return dataGraduou;
}
public void setDataGraduou(Date dataGraduou) {
this.dataGraduou = dataGraduou;
}
#Override
public int hashCode() {
int hash = 3;
hash = 59 * hash + Objects.hashCode(this.aluno);
hash = 59 * hash + Objects.hashCode(this.graduacao);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final HistoricoDeGraduacao other = (HistoricoDeGraduacao) obj;
if (!Objects.equals(this.aluno, other.aluno)) {
return false;
}
if (!Objects.equals(this.graduacao, other.graduacao)) {
return false;
}
return true;
}
}
//aqui meu jframe com seus componentes, pegando valores montando tudo para ser salvo
historico.setDataGraduou(jdp_dataGraduou.getDate());
historico.setGrau(jl_graus.getSelectedValue().toString());
//pega graduacao do jcombobox
Graduacao g = (Graduacao)cbx_graduacao.getSelectedItem();
historico.setGraduacao(g);
//bean aluno
historico.setAluno(bean);
//add a listas
bean.addListaHistoricoGraduacao(historico);
g.addHistoricoDeGraduacao(historico);
//inicia instancia de pk e insere o proximo id
historico.begin();
//salva tudo
new HistoricoDeGraduacaoDAO().update(historico);
//aqui meu DAO
public class HistoricoDeGraduacaoDAO {
private EntityManager em;
public HistoricoDeGraduacaoDAO(){
em = Persistencia.getEntityManager();
}
/** pega o ultimo valor da tabela HistoricoDeGraduacao e adiciona + 1 para o proximo indice */
public Integer getIndex(){
int count = 0;
Query query = em.createQuery("SELECT MAX(hdg.pk.id) FROM HistoricoDeGraduacao hdg");
if(query.getSingleResult() == null){
++count;
}else{
count = (int)query.getSingleResult() + 1;
}
return count;
}
/** executa update */
public void update(HistoricoDeGraduacao historico){
try{
em.getTransaction().begin();
em.merge(historico);
em.getTransaction().commit();
}catch(PersistenceException e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}finally{
em.close();
}
}
}
And result is:
Related
I'm having some trouble to find out how to use an specific query on Springboot
SELECT tb_excursao.fk_cliente, tb_cliente.nome, tb_cliente.documento, tb_cliente.org_emissor, tb_cliente.data_nascimento, tb_excursao.fk_viagem, tb_viagens.destino, tb_viagens.data_viagem
FROM ((tb_excursao
INNER JOIN tb_cliente ON fk_cliente = tb_cliente.id_cliente)
INNER JOIN tb_viagens ON fk_viagem = tb_viagens.id_viagem))
This works fine on MySQL, but the examples that I saw it's always something like "SELECT u FROM User u", and as a beginner I can't relate using columns from different tables using #Query.
The models are below:
Cliente.java
#Entity
#Table(name = "tb_cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idCliente;
#NotBlank
#Size(min = 3)
private String nome;
#NotNull
private String documento;
#NotNull
private String orgEmissor;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataNascimento;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro = new java.sql.Date(System.currentTimeMillis());
#OneToMany(mappedBy = "fkCliente")
Set<Excursao> excursao;
public long getIdCliente() {
return idCliente;
}
public void setIdCliente(long idCliente) {
this.idCliente = idCliente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getOrgEmissor() {
return orgEmissor;
}
public void setOrgEmissor(String orgEmissor) {
this.orgEmissor = orgEmissor;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
}
Viagem.java
#Entity
#Table(name = "tb_viagens")
public class Viagem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idViagem;
#NotBlank
private String destino;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataViagem;
#NotBlank
private int quantidadeMaxPessoas;
#OneToMany(mappedBy = "fkViagem")
private Set<Excursao> excursao;
public long getIdViagem() {
return idViagem;
}
public void setIdViagem(long idViagem) {
this.idViagem = idViagem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public Date getDataViagem() {
return dataViagem;
}
public void setDataViagem(Date dataViagem) {
this.dataViagem = dataViagem;
}
public int getQuantidadeMaxPessoas() {
return quantidadeMaxPessoas;
}
public void setQuantidadeMaxPessoas(int quantidadeMaxPessoas) {
this.quantidadeMaxPessoas = quantidadeMaxPessoas;
}
}
ExcursaoEmbeddable.java
#Embeddable
public class ExcursaoEmb implements Serializable {
#Column(name = "fkCliente")
private Long fkCliente;
#Column(name = "fkViagem")
private Long fkViagem;
public Long getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Long fkCliente) {
this.fkCliente = fkCliente;
}
public Long getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Long fkViagem) {
this.fkViagem = fkViagem;
}
}
Excursao.java This is the table that the query in the beginning of the post goes
#Entity
#Table(name = "tb_excursao")
public class Excursao {
#EmbeddedId
ExcursaoEmb idExcursao;
#ManyToOne
#JoinColumn(name = "id_cliente")
private Cliente fkCliente;
#ManyToOne
#JoinColumn(name = "id_viagem")
private Viagem fkViagem;
#NotNull
private boolean primeiraParcela;
#NotNull
private boolean segundaParcela;
private boolean terceiraParcela;
public ExcursaoEmb getIdExcursao() {
return this.idExcursao;
}
public void setIdExcursao(ExcursaoEmb idExcursao) {
this.idExcursao = idExcursao;
}
public Cliente getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Cliente fkCliente) {
this.fkCliente = fkCliente;
}
public Viagem getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Viagem fkViagem) {
this.fkViagem = fkViagem;
}
public boolean isPrimeiraParcela() {
return this.primeiraParcela;
}
public boolean getPrimeiraParcela() {
return this.primeiraParcela;
}
public void setPrimeiraParcela(boolean primeiraParcela) {
this.primeiraParcela = primeiraParcela;
}
public boolean isSegundaParcela() {
return this.segundaParcela;
}
public boolean getSegundaParcela() {
return this.segundaParcela;
}
public void setSegundaParcela(boolean segundaParcela) {
this.segundaParcela = segundaParcela;
}
public boolean isTerceiraParcela() {
return this.terceiraParcela;
}
public boolean getTerceiraParcela() {
return this.terceiraParcela;
}
public void setTerceiraParcela(boolean terceiraParcela) {
this.terceiraParcela = terceiraParcela;
}
}
I have a request table related to 2 tables where I save the request number according to the type of request that can be a request for water analysis and request for soil analysis, but when I try to delete or update the request table I get the error
Cannot delete or update a parent row: a foreign key constraint fails
My code that implements the relationships is the following is the following
//class for request
#Entity
#Table(name = "solicitud")
public class Solicitud implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
//#Column(unique=true)
//private String codigo;
#ManyToOne(fetch = FetchType.LAZY)
private Estado estado;
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
#NotNull
#Column(name="fecha")
private Date fecha;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Usuario usuario;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Usuario teclab;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private TipoMuestra tmuestra;
//#Min(value = 0L, message = "Debe ingresar un valor positivo")
//#Pattern(regexp = "[\\s]*[0-9]*[1-9]+",message="msg")
#NotNull
private Integer numMuestras;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Estado getEstado() {
return estado;
}
public void setEstado(Estado estado) {
this.estado = estado;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public TipoMuestra getTmuestra() {
return tmuestra;
}
public void setTmuestra(TipoMuestra tmuestra) {
this.tmuestra = tmuestra;
}
public Integer getNumMuestras() {
return numMuestras;
}
public void setNumMuestras(Integer numMuestras) {
this.numMuestras = numMuestras;
}
public Usuario getTeclab() {
return teclab;
}
public void setTeclab(Usuario teclab) {
this.teclab = teclab;
}
/*#PostPersist
public void generateCode() {
CodigoAgua agua=new CodigoAgua();
agua.setSolicitud(this);
agua.generateCode();
}*/
/**
*
*/
private static final long serialVersionUID = 1L;
}
//class for save number for type request water analysis
#Entity
#Table(name = "cagua")
public class CodigoAgua implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique=true)
private String codigo;
#OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="solicitud_id")
private Solicitud solicitud;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Solicitud getSolicitud() {
return solicitud;
}
public void setSolicitud(Solicitud solicitud) {
this.solicitud = solicitud;
}
#PostPersist
public void generateCode() {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
this.codigo=year +" - "+id+" - A";
System.out.println("Codigo solicitud creado"+id+this.getSolicitud().getId());
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
//class for save number for type request soil analysis
#Entity
#Table(name = "csuelo")
public class CodigoSuelo implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique=true)
private String codigo;
#OneToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="solicitud_id")
private Solicitud solicitud;
int year = 0;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public Solicitud getSolicitud() {
return solicitud;
}
public void setSolicitud(Solicitud solicitud) {
this.solicitud = solicitud;
}
#PostPersist
public void generateCode() {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
this.codigo=year +" - "+id+" - S";
System.out.println("Codigo solicitud creado"+id+this.getSolicitud().getId());
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
This message indicates that you want to delete a row from table1, while its primary key is present as a foreign key in table2.
To delete a record from table1, you must delete all the lines that refer to it in the other tables in order to be able to delete this record.
I hope I've helped you
I have this model with 2 tables, "Cuenta" and "Movimien". When the merge () method of the Movimien table is called, it also attempts to insert into the Cuenta table. I am not sure if relationships are right. Could someone give me a hand with this?
Below, the model of the Movimien table, which when doing the update triggers the insert in the Cuenta table:
#Entity
#Table(name = "movimien")
public class Movimien implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Date fecha;
private short cuentaid;
private float importe;
private String concepto;
#JoinColumn(name = "cuentaid", insertable = false, updatable = false)
#ManyToOne
private Cuenta cuenta;
public Movimien() {
this.cuenta = new Cuenta();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public short getCuentaid() {
return cuentaid;
}
public void setCuentaid(short cuentaid) {
this.cuentaid = cuentaid;
}
public float getImporte() {
return importe;
}
public void setImporte(float importe) {
this.importe = importe;
}
public String getConcepto() {
return concepto;
}
public void setConcepto(String concepto) {
this.concepto = concepto;
}
public Cuenta getCuenta() {
return cuenta;
}
public void setCuenta(Cuenta cuenta) {
this.cuenta = cuenta;
}
#Override
public int hashCode() {
int hash = 7;
hash = 53 * hash + this.id;
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Movimien other = (Movimien) obj;
if (this.id != other.id) {
return false;
}
return true;
}}
And the model of the Cuenta table, to which the insert is triggered when an update is made in the Movimien table:
#Entity
#Table(name = "cuentas")
public class Cuenta implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nombre;
private short tipo;
#OneToMany(mappedBy="cuenta")
private List<Movimien> movimien;
public Cuenta() {
this.nombre="";
this.tipo = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public short getTipo() {
return tipo;
}
public void setTipo(short tipo) {
this.tipo = tipo;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + this.id;
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cuenta other = (Cuenta) obj;
if (this.id != other.id) {
return false;
}
return true;
}}
Any idea what may be the reason for this behavior?,
thanks in advance!
Fernando
Persitence.xml
Database
Log of update and insert
These are my model classes:
Film.java
#Entity
public class Film {
private Integer id;
private String title;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "film")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
Actor.java
#Entity
public class Actor {
private Integer id;
private String firstname;
private String lastname;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "actor")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
And this is the Join Table Entity:
#Entity
#Table(name = "film_actor")
public class FilmActor {
private FilmActorPK id;
private Film film;
private Actor actor;
private Timestamp lastUpdate;
#EmbeddedId
public FilmActorPK getId() {
return id;
}
public void setId(FilmActorPK id) {
this.id = id;
}
#ManyToOne
#MapsId("film")
#JoinColumn(name = "film_id")
public Film getFilm() {
return film;
}
public void setFilm(Film film) {
this.film = film;
}
#ManyToOne
#MapsId("actor")
#JoinColumn(name = "actor_id")
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
#Column(name = "last_update")
public Timestamp getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
and the Primary Key class:
#Embeddable
public class FilmActorPK implements Serializable {
private int actorId;
private int filmId;
#Column(name = "actor_id")
public int getActorId() {
return actorId;
}
public void setActorId(int actorId) {
this.actorId = actorId;
}
#Column(name = "film_id")
public int getFilmId() {
return filmId;
}
public void setFilmId(int filmId) {
this.filmId = filmId;
}
}
So I want to find films where 2 given actors acts. This is what I have:
#Override
public Collection<Film> filmsActorsTogether(Actor a, Actor b) {
final List<Film> filmsOfActorA = filmsOfActor(a);
final List<Film> filmsOfActorB = filmsOfActor(b);
final Collection<Film> intersection = CollectionUtils.intersection(filmsOfActorA, filmsOfActorB);
return intersection;
}
#Override
public List<Film> filmsOfActor(Actor actor) {
final EntityManager entityManager = persistenceUtil.getEntityManager();
final Actor persistentActor = entityManager.find(Actor.class, actor.getId());
final ArrayList<Film> films = new ArrayList<Film>();
for (FilmActor filmActor : persistentActor.getFilmActors()) {
films.add(filmActor.getFilm());
}
entityManager.close();
return films;
}
Is there any way to achieve this without fetching ALL films of 2 actors, and using filtering in memory? How do I get the Films directly from the DB with JQL?
Maybe there is something more elegant, but the following query should work:
select f from Film f where
(select count(fa.id) from FilmActor fa
where fa.film = f
and (fa.actor = :actor1 or fa.actor = :actor2)) = 2
Side note: your PK class should have a correct equals() and hashCode() methods
I'm trying implement a rest service. I have created my entitys and daos, and when use this everthyng works fine.
But when I trye expose the information in rest json, the infinite recursion error occur.
I have read many topic about this error, but not is so clear for me.
I'm have tried so many alternatives that is hard talk about each.
When I debug my code, I see that the data from dao is correctly, the problem occur when I trie use json. Whe I use jsf page works fine.
I have tried use Gson and return String in my rest method, but stackoverflow error occur to.
Bellow I post my implememtation (all), because a dont have idea about the problem.
I using wildfly server...
Thanks in advance
Model's
#Entity
#Table(name="usertable")
#NamedQuery(name="UserModel.findAll", query="SELECT u FROM UserModel u")
#XmlRootElement
public class UserModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String USId;
#Temporal(TemporalType.DATE)
#Column(nullable=false)
private Date userNascimento;
#Column(nullable=false, length=45)
private String USMail;
#Column(nullable=false, length=150)
private String USName;
#Column(nullable=false, length=45)
private String USNick;
#Column(nullable=false, length=45)
private String USPassword;
//bi-directional many-to-one association to UserAddressModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="usertable")
private List<UserAddressModel> listAddressModel;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="usertable")
private List<UserFoneModel> listFoneModel;
public UserModel() {
}
public String getUSId() {
return this.USId;
}
public void setUSId(String USId) {
this.USId = USId;
}
public Date getUserNascimento() {
return this.userNascimento;
}
public void setUserNascimento(Date userNascimento) {
this.userNascimento = userNascimento;
}
public String getUSMail() {
return this.USMail;
}
public void setUSMail(String USMail) {
this.USMail = USMail;
}
public String getUSName() {
return this.USName;
}
public void setUSName(String USName) {
this.USName = USName;
}
public String getUSNick() {
return this.USNick;
}
public void setUSNick(String USNick) {
this.USNick = USNick;
}
public String getUSPassword() {
return this.USPassword;
}
public void setUSPassword(String USPassword) {
this.USPassword = USPassword;
}
public List<UserAddressModel> getUseraddresstables() {
return this.listAddressModel;
}
public void setUseraddresstables(List<UserAddressModel> useraddresstables) {
this.listAddressModel = useraddresstables;
}
public UserAddressModel addUseraddresstable(UserAddressModel useraddresstable) {
getUseraddresstables().add(useraddresstable);
useraddresstable.setUsertable(this);
return useraddresstable;
}
public UserAddressModel removeUseraddresstable(UserAddressModel useraddresstable) {
getUseraddresstables().remove(useraddresstable);
useraddresstable.setUsertable(null);
return useraddresstable;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setUsertable(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setUsertable(null);
return userfonetable;
}
}
#Entity
#Table(name="userfonetable")
#NamedQuery(name="UserFoneModel.findAll", query="SELECT u FROM UserFoneModel u")
public class UserFoneModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String UFId;
#Column(nullable=false)
private short UFDdd;
#Column(nullable=false)
private int UFFone;
//bi-directional many-to-one association to UserModel
#ManyToOne
#JoinColumn(name="UFUserID", nullable=false)
private UserModel usertable;
//bi-directional many-to-one association to OperadorasModel
#ManyToOne
#JoinColumn(name="UFOperadoraID", nullable=false)
private OperadorasModel operadorastable;
//bi-directional many-to-one association to TiposFoneModel
#ManyToOne
#JoinColumn(name="UFTipoTelefone", nullable=false)
private TiposFoneModel tbTipostelefone;
public UserFoneModel() {
}
public String getUFId() {
return this.UFId;
}
public void setUFId(String UFId) {
this.UFId = UFId;
}
public short getUFDdd() {
return this.UFDdd;
}
public void setUFDdd(short UFDdd) {
this.UFDdd = UFDdd;
}
public int getUFFone() {
return this.UFFone;
}
public void setUFFone(int UFFone) {
this.UFFone = UFFone;
}
public UserModel getUsertable() {
return this.usertable;
}
public void setUsertable(UserModel usertable) {
this.usertable = usertable;
}
public OperadorasModel getOperadorastable() {
return this.operadorastable;
}
public void setOperadorastable(OperadorasModel operadorastable) {
this.operadorastable = operadorastable;
}
public TiposFoneModel getTbTipostelefone() {
return this.tbTipostelefone;
}
public void setTbTipostelefone(TiposFoneModel tbTipostelefone) {
this.tbTipostelefone = tbTipostelefone;
}
}
#Entity
#Table(name="useraddresstable")
#NamedQuery(name="UserAddressModel.findAll", query="SELECT u FROM UserAddressModel u")
public class UserAddressModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private String UAId;
#Column(nullable=false, length=100)
private String UABairro;
#Column(nullable=false, length=100)
private String UACidade;
#Column(length=45)
private String UAComplemento;
#Column(nullable=false, length=2)
private String UAEstado;
#Column(nullable=false)
private int UANumero;
#Column(length=100)
private String UARua;
//bi-directional many-to-one association to UserModel
#ManyToOne
#JoinColumn(name="UAUserID", nullable=false)
private UserModel usertable;
public UserAddressModel() {
}
public String getUAId() {
return this.UAId;
}
public void setUAId(String UAId) {
this.UAId = UAId;
}
public String getUABairro() {
return this.UABairro;
}
public void setUABairro(String UABairro) {
this.UABairro = UABairro;
}
public String getUACidade() {
return this.UACidade;
}
public void setUACidade(String UACidade) {
this.UACidade = UACidade;
}
public String getUAComplemento() {
return this.UAComplemento;
}
public void setUAComplemento(String UAComplemento) {
this.UAComplemento = UAComplemento;
}
public String getUAEstado() {
return this.UAEstado;
}
public void setUAEstado(String UAEstado) {
this.UAEstado = UAEstado;
}
public int getUANumero() {
return this.UANumero;
}
public void setUANumero(int UANumero) {
this.UANumero = UANumero;
}
public String getUARua() {
return this.UARua;
}
public void setUARua(String UARua) {
this.UARua = UARua;
}
public UserModel getUsertable() {
return this.usertable;
}
public void setUsertable(UserModel usertable) {
this.usertable = usertable;
}
}
#Entity
#Table(name="tb_tipostelefone")
#NamedQuery(name="TiposFoneModel.findAll", query="SELECT t FROM TiposFoneModel t")
public class TiposFoneModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private short TFId;
#Column(nullable=false, length=45)
private String TFDescricao;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="tbTipostelefone")
private List<UserFoneModel> listFoneModel;
public TiposFoneModel() {
}
public short getTFId() {
return this.TFId;
}
public void setTFId(short TFId) {
this.TFId = TFId;
}
public String getTFDescricao() {
return this.TFDescricao;
}
public void setTFDescricao(String TFDescricao) {
this.TFDescricao = TFDescricao;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setTbTipostelefone(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setTbTipostelefone(null);
return userfonetable;
}
}
#Entity
#Table(name="operadorastable")
#NamedQuery(name="OperadorasModel.findAll", query="SELECT o FROM OperadorasModel o")
public class OperadorasModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(unique=true, nullable=false)
private short OPCodigo;
#Column(nullable=false, length=100)
private String opNome;
//bi-directional many-to-one association to UserFoneModel
#OneToMany(fetch = FetchType.EAGER, mappedBy="operadorastable")
private List<UserFoneModel> listFoneModel;
public OperadorasModel() {
}
public short getOPCodigo() {
return this.OPCodigo;
}
public void setOPCodigo(short OPCodigo) {
this.OPCodigo = OPCodigo;
}
public String getOpNome() {
return this.opNome;
}
public void setOpNome(String opNome) {
this.opNome = opNome;
}
public List<UserFoneModel> getUserfonetables() {
return this.listFoneModel;
}
public void setUserfonetables(List<UserFoneModel> userfonetables) {
this.listFoneModel = userfonetables;
}
public UserFoneModel addUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().add(userfonetable);
userfonetable.setOperadorastable(this);
return userfonetable;
}
public UserFoneModel removeUserfonetable(UserFoneModel userfonetable) {
getUserfonetables().remove(userfonetable);
userfonetable.setOperadorastable(null);
return userfonetable;
}
}
DAO
#Stateless
#LocalBean
public class UserDao {
/**
* Default constructor.
*/
#PersistenceContext
EntityManager em;
public UserDao() {
// TODO Auto-generated constructor stub
}
public List<UserModel> listAll()
{
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserModel> cq = cb.createQuery(UserModel.class);
Root<UserModel> rootEntry = cq.from(UserModel.class);
CriteriaQuery<UserModel> all = cq.select(rootEntry);
TypedQuery<UserModel> allQuery = em.createQuery(all);
List<UserModel> listU = allQuery.getResultList();
return listU;
/*
Query query = em.createQuery("SELECT u FROM UserModel u");
return query.getResultList();
*/
}
}
My Rest
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import br.com.avera.dao.UserDao;
import br.com.avera.model.UserAddressModel;
import br.com.avera.model.UserFoneModel;
import br.com.avera.model.UserModel;
#Path("/users")
public class UserRest {
#Inject
UserDao userDao;
#GET
#Produces(MediaType.APPLICATION_JSON)
public UserModel getUser()
{
List<UserModel> userModelList = userDao.listAll();
UserModel userModel = userModelList.get(0);
List<UserFoneModel> lFone = userModel.getUserfonetables();
for (UserFoneModel userFoneModel : lFone) {
System.out.println(userFoneModel.getUFDdd());
System.out.println(userFoneModel.getUFFone());
}
System.out.println("OOOOOO");
List<UserAddressModel> lAddressModels = userModel.getUseraddresstables();
for (UserAddressModel userAddressModel : lAddressModels) {
System.out.println(userAddressModel.getUACidade());
System.out.println(userAddressModel.getUAEstado());
}
return userModel;
}
}