Use Ormlite for JOIN 2 tables - ormlite

when I use pedidoQb.join(clientQb).prepareStatementString();, returns SELECT pedido.* FROM pedido INNER JOIN cliente ON pedido.idcliente = cliente.idCliente WHERE cliente.nomeRazao LIKE 'MARIA'
ok, perfect.
when I use
`#Override
public List<Pedido> list(Pedido pedido) throws SQLException {
QueryBuilder<Pedido, Integer> pedidoQb = this.getDaoDB().queryBuilder();
QueryBuilder<Cliente, Integer> clientQb = ((DAOImplementation)new DAOFactory().getClienteDAO(this.getContext())).getDaoDB().queryBuilder();
clientQb.where().like("nomeRazao", "ANA");
// select * from cliente inner join pedido on cliente.idcliente = pedido.idcliente where cliente.nomerazao like "%nome%";
return pedidoQb.join(clientQb).query();
}`
select generated
Problems executing Android query: SELECT `pedido`.* FROM `pedido` INNER JOIN `cliente` ON `pedido`.`idcliente` = `cliente`.`idCliente` INNER JOIN `cliente` ON `pedido`.`idcliente` = `cliente`.`idCliente` WHERE `cliente`.`nomeRazao` LIKE 'MARIA' AND (`cliente`.`nomeRazao` LIKE 'MARIA' )
error:
(1) ambiguous column name: cliente.nomeRazao
What did the wrong?
object Pedido
#DatabaseTable(tableName = "pedido")
public class Pedido implements Serializable {
#DatabaseField(unique = true, id = true)
private Integer idPedido;
#DatabaseField
private Date dataPedido;
#DatabaseField
private Date dataVencimento;
#DatabaseField
private Date dataBrinde;
/**
* Integer idViagemPedido
*
* Chave foregnKey da tabela Viagem(idViagem)
* Viagem que o pedido foi feito
* Quando cadastrado no tablet deve assumir o valor
* que existe na tabela Viagem.
* Quando vier da API virá com o id da viagem que foi feito
*/
#DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "idviagem", columnDefinition = "integer references viagem(idViagem)")
private Viagem idViagemPedido;
/**
* Integer idCliente
*
* Chave foregnKey da tabela Cliente(idCliente)
*/
#DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "idcliente", columnDefinition = "integer references cliente(idCliente)")
private Cliente idCliente;
/**
* Integer idCobrador
*
* Chave foregnKey da tabela Viagem(idCobrador)
* Quando cadastrado no android deve assumir o valor
* que contém na tabela Viagem.
* Quando for integrado da API terá o id do cobrador da viagem do pedido.
*/
//#DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "idcobrador", columnDefinition = "integer references viagem(idCobrador)")
#DatabaseField
private Integer idCobrador;
/**
* Integer idVendedor
*
* Quando cadastrado no android deve assumir o valor
* do idCobrador, isso é se foi feito por um cobrador.
*/
#DatabaseField
private Integer idVendedor;
/**
* Integer idTampeiro
*
* Quando cadastrado no android deve assumir o valor
* de qual Tampeiro do pedido.
* Se houver mais de um tampeiro na viagem deve aparecer
* para o cobrador escolher, se não pegar o valor do contido
* na tabela Viagem.
*/
#DatabaseField
private Integer idTampeiro;
#DatabaseField
private Double percDevolucao;
#DatabaseField
private Double percBrinde;
#DatabaseField
private Double totalConsignado;
#DatabaseField
private Double totalVendido;
#DatabaseField
private Double totalTrocaEntrada;
#DatabaseField
private Double totalTrocaSaida;
#DatabaseField
private Double totalBrinde;
#DatabaseField
private Double totalAcrescimo;
#DatabaseField
private Double totalDesconto;
#DatabaseField
private Double totalLiquido;
#DatabaseField
private Double totalPago;
#DatabaseField
private Double totalApagar;
#DatabaseField
private Integer status;
#DatabaseField
private Integer statusNovo; // 0 -> não é novo, 1 -> é novo
/***********************************************
* Initiation of methods
***********************************************/
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getIdPedido()
{
return idPedido;
}
public void setIdPedido(Integer idPedido)
{
this.idPedido = idPedido;
}
public Date getDataPedido()
{
return dataPedido;
}
public void setDataPedido(Date dataPedido)
{
this.dataPedido = dataPedido;
}
public Date getDataVencimento()
{
return dataVencimento;
}
public void setDataVencimento(Date dataVencimento)
{
this.dataVencimento = dataVencimento;
}
public Date getDataBrinde()
{
return dataBrinde;
}
public void setDataBrinde(Date dataBrinde)
{
this.dataBrinde = dataBrinde;
}
public Viagem getIdViagemPedido()
{
return idViagemPedido;
}
public void setIdViagemPedido(Viagem idViagemPedido)
{
this.idViagemPedido = idViagemPedido;
}
public Cliente getIdCliente()
{
return idCliente;
}
public void setIdCliente(Cliente idCliente)
{
this.idCliente = idCliente;
}
public Integer getIdCobrador()
{
return idCobrador;
}
public void setIdCobrador(Integer idCobrador)
{
this.idCobrador = idCobrador;
}
public Integer getIdVendedor()
{
return idVendedor;
}
public void setIdVendedor(Integer idVendedor)
{
this.idVendedor = idVendedor;
}
public Integer getIdTampeiro()
{
return idTampeiro;
}
public void setIdTampeiro(Integer idTampeiro)
{
this.idTampeiro = idTampeiro;
}
public Double getPercDevolucao()
{
return percDevolucao;
}
public void setPercDevolucao(Double percDevolucao)
{
this.percDevolucao = percDevolucao;
}
public Double getPercBrinde()
{
return percBrinde;
}
public void setPercBrinde(Double percBrinde)
{
this.percBrinde = percBrinde;
}
public Double getTotalConsignado()
{
return totalConsignado;
}
public void setTotalConsignado(Double totalConsignado)
{
this.totalConsignado = totalConsignado;
}
public Double getTotalVendido()
{
return totalVendido;
}
public void setTotalVendido(Double totalVendido)
{
this.totalVendido = totalVendido;
}
public Double getTotalTrocaEntrada()
{
return totalTrocaEntrada;
}
public void setTotalTrocaEntrada(Double totalTrocaEntrada)
{
this.totalTrocaEntrada = totalTrocaEntrada;
}
public Double getTotalTrocaSaida()
{
return totalTrocaSaida;
}
public void setTotalTrocaSaida(Double totalTrocaSaida)
{
this.totalTrocaSaida = totalTrocaSaida;
}
public Double getTotalBrinde()
{
return totalBrinde;
}
public void setTotalBrinde(Double totalBrinde)
{
this.totalBrinde = totalBrinde;
}
public Double getTotalAcrescimo()
{
return totalAcrescimo;
}
public void setTotalAcrescimo(Double totalAcrescimo)
{
this.totalAcrescimo = totalAcrescimo;
}
public Double getTotalDesconto()
{
return totalDesconto;
}
public void setTotalDesconto(Double totalDesconto)
{
this.totalDesconto = totalDesconto;
}
public Double getTotalLiquido()
{
return totalLiquido;
}
public void setTotalLiquido(Double totalLiquido)
{
this.totalLiquido = totalLiquido;
}
public Double getTotalPago()
{
return totalPago;
}
public void setTotalPago(Double totalPago)
{
this.totalPago = totalPago;
}
public Double getTotalApagar()
{
return totalApagar;
}
public void setTotalApagar(Double totalApagar)
{
this.totalApagar = totalApagar;
}
public Integer getStatusNovo() {
return statusNovo;
}
public void setStatusNovo(Integer statusNovo) {
this.statusNovo = statusNovo;
}
}
#DatabaseTable
public class Cliente implements Serializable {
#SerializedName(value = "id_cliente")
#DatabaseField(canBeNull = false, unique = true, id = true)
private Integer idCliente;
#SerializedName(value = "data_cadastro")
#DatabaseField
private Date dataCadastro;
#SerializedName(value = "tipo_pessoa")
#DatabaseField(width = 1)
private String tipoPessoa;
#SerializedName(value = "nome_razao")
#DatabaseField(width = 60, canBeNull = true)
private String nomeRazao;
#SerializedName(value = "nome_fantasia")
#DatabaseField(width = 60)
private String nomeFantasia;
#SerializedName(value = "nome_responsavel")
#DatabaseField(width = 60)
private String nomeResponsavel;
#DatabaseField(width = 14, uniqueIndex = true)
private String cpf;
#DatabaseField(width = 14, uniqueIndex = true)
private String cnpj;
#DatabaseField(width = 14)
private String ie;
#DatabaseField(width = 14)
private String rg;
#SerializedName(value = "orgao_expedidor")
#DatabaseField(width = 10)
private String orgaoExpedidor;
#SerializedName(value = "data_nascimento")
#DatabaseField
private Date dataNascimento;
#SerializedName(value = "nome_pai")
#DatabaseField(width = 60)
private String nomePai;
#SerializedName(value = "nome_mae")
#DatabaseField(width = 60)
private String nomeMae;
#DatabaseField(width = 14)
private String fone1;
#DatabaseField(width = 14)
private String fone2;
#DatabaseField(width = 60)
private String email;
#DatabaseField(width = 2)
private String uf;
#SerializedName(value = "id_cidade")
#DatabaseField
private Integer idCidade;
#DatabaseField(width = 8)
private String cep;
#DatabaseField(width = 60)
private String endereco;
#DatabaseField(width = 60)
private String bairro;
#DatabaseField(width = 6)
private String numero;
#DatabaseField(width = 35)
private String referencia;
#DatabaseField
private Integer novoCliente;
public Integer getIdCliente() {
return idCliente;
}
public void setIdCliente(Integer idCliente) {
this.idCliente = idCliente;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
public String getTipoPessoa() {
return tipoPessoa;
}
public void setTipoPessoa(String tipoPessoa) {
this.tipoPessoa = tipoPessoa;
}
public String getNomeRazao() {
return nomeRazao;
}
public void setNomeRazao(String nomeRazao) {
this.nomeRazao = nomeRazao;
}
public String getNomeFantasia() {
return nomeFantasia;
}
public void setNomeFantasia(String nomeFantasia) {
this.nomeFantasia = nomeFantasia;
}
public String getNomeResponsavel() {
return nomeResponsavel;
}
public void setNomeResponsavel(String nomeResponsavel) {
this.nomeResponsavel = nomeResponsavel;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getCnpj() {
return cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
public String getIe() {
return ie;
}
public void setIe(String ie) {
this.ie = ie;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getOrgaoExpedidor() {
return orgaoExpedidor;
}
public void setOrgaoExpedidor(String orgaoExpedidor) {
this.orgaoExpedidor = orgaoExpedidor;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getNomePai() {
return nomePai;
}
public void setNomePai(String nomePai) {
this.nomePai = nomePai;
}
public String getNomeMae() {
return nomeMae;
}
public void setNomeMae(String nomeMae) {
this.nomeMae = nomeMae;
}
public String getFone1() {
return fone1;
}
public void setFone1(String fone1) {
this.fone1 = fone1;
}
public String getFone2() {
return fone2;
}
public void setFone2(String fone2) {
this.fone2 = fone2;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public Integer getIdCidade() {
return idCidade;
}
public void setIdCidade(Integer idCidade) {
this.idCidade = idCidade;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getReferencia() {
return referencia;
}
public void setReferencia(String referencia) {
this.referencia = referencia;
}
public Integer getNovoCliente() {
return novoCliente;
}
public void setNovoCliente(Integer novoCliente) {
this.novoCliente = novoCliente;
}
}
error complet
07-15 19:55:53.976 1603-1603/br.com.forcavenda E/SQLiteLog﹕ (1) ambiguous column name: cliente.nomeRazao
07-15 19:55:53.976 1603-1603/br.com.forcavenda W/System.err﹕ java.sql.SQLException: Problems executing Android query: SELECT pedido.* FROM pedido INNER JOIN cliente ON pedido.idcliente = cliente.idCliente INNER JOIN cliente ON pedido.idcliente = cliente.idCliente WHERE cliente.nomeRazao LIKE 'ANA' AND (cliente.nomeRazao LIKE 'ANA' )
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:22)
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.android.AndroidCompiledStatement.getCursor(AndroidCompiledStatement.java:184)
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.android.AndroidCompiledStatement.runQuery(AndroidCompiledStatement.java:65)
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.stmt.SelectIterator.<init>(SelectIterator.java:55)
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java:247)
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:196)
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.dao.BaseDaoImpl.query(BaseDaoImpl.java:265)
07-15 19:55:53.980 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.stmt.QueryBuilder.query(QueryBuilder.java:361)
07-15 19:55:53.984 1603-1603/br.com.forcavenda W/System.err﹕ at br.com.forcavenda.storage.dao.implementacao.PedidoDAOImplementation.list(PedidoDAOImplementation.java:62)
07-15 19:55:53.984 1603-1603/br.com.forcavenda W/System.err﹕ at br.com.forcavenda.controllers.implementation.PedidoControllerImplementation.list(PedidoControllerImplementation.java:54)
07-15 19:55:53.984 1603-1603/br.com.forcavenda W/System.err﹕ at br.com.forcavenda.view.ListaPedidoActivity$PlaceholderFragment.atualizarListaPedido(ListaPedidoActivity.java:108)
07-15 19:55:53.984 1603-1603/br.com.forcavenda W/System.err﹕ at br.com.forcavenda.view.ListaPedidoActivity$PlaceholderFragment.onCreateView(ListaPedidoActivity.java:81)
07-15 19:55:53.984 1603-1603/br.com.forcavenda W/System.err﹕ at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
07-15 19:55:53.984 1603-1603/br.com.forcavenda W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
07-15 19:55:53.988 1603-1603/br.com.forcavenda W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
07-15 19:55:53.988 1603-1603/br.com.forcavenda W/System.err﹕ at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
07-15 19:55:53.992 1603-1603/br.com.forcavenda W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
07-15 19:55:53.992 1603-1603/br.com.forcavenda W/System.err﹕ at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:571)
07-15 19:55:53.992 1603-1603/br.com.forcavenda W/System.err﹕ at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
07-15 19:55:53.996 1603-1603/br.com.forcavenda W/System.err﹕ at android.app.Activity.performStart(Activity.java:5018)
07-15 19:55:53.996 1603-1603/br.com.forcavenda W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
07-15 19:55:53.996 1603-1603/br.com.forcavenda W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
07-15 19:55:53.996 1603-1603/br.com.forcavenda W/System.err﹕ at android.app.ActivityThread.access$600(ActivityThread.java:130)
07-15 19:55:54.000 1603-1603/br.com.forcavenda W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
07-15 19:55:54.000 1603-1603/br.com.forcavenda W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
07-15 19:55:54.000 1603-1603/br.com.forcavenda W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
07-15 19:55:54.004 1603-1603/br.com.forcavenda W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4745)
07-15 19:55:54.004 1603-1603/br.com.forcavenda W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
07-15 19:55:54.004 1603-1603/br.com.forcavenda W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
07-15 19:55:54.008 1603-1603/br.com.forcavenda W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-15 19:55:54.008 1603-1603/br.com.forcavenda W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-15 19:55:54.008 1603-1603/br.com.forcavenda W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
07-15 19:55:54.008 1603-1603/br.com.forcavenda W/System.err﹕ Caused by: android.database.sqlite.SQLiteException: ambiguous column name: cliente.nomeRazao (code 1): , while compiling: SELECT pedido.* FROM pedido INNER JOIN cliente ON pedido.idcliente = cliente.idCliente INNER JOIN cliente ON pedido.idcliente = cliente.idCliente WHERE cliente.nomeRazao LIKE 'ANA' AND (cliente.nomeRazao LIKE 'ANA' )
07-15 19:55:54.012 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
07-15 19:55:54.012 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
07-15 19:55:54.012 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
07-15 19:55:54.016 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
07-15 19:55:54.016 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
07-15 19:55:54.016 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
07-15 19:55:54.020 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
07-15 19:55:54.020 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
07-15 19:55:54.020 1603-1603/br.com.forcavenda W/System.err﹕ at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
07-15 19:55:54.020 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.android.compat.JellyBeanApiCompatibility.rawQuery(JellyBeanApiCompatibility.java:21)
07-15 19:55:54.020 1603-1603/br.com.forcavenda W/System.err﹕ at com.j256.ormlite.android.AndroidCompiledStatement.getCursor(AndroidCompiledStatement.java:180)
07-15 19:55:54.020 1603-1603/br.com.forcavenda W/System.err﹕ ... 30 more
07-15 19:55:54.028 1603-1603/br.com.forcavenda I/Choreographer﹕ Skipped 1301 frames! The application may be doing too much work on its main thread.
07-15 19:55:54.104 1603-1603/br.com.forcavenda W/EGL_emulation﹕ eglSurfaceAttrib not implemented

Solved!
#Override
public List<Pedido> list(Pedido pedido) throws SQLException {
QueryBuilder<Pedido, Integer> pedidoQb = this.getDaoDB().queryBuilder();
QueryBuilder<Cliente, Integer> clientQb = ((DAOImplementation)new DAOFactory().getClienteDAO(this.getContext())).getDaoDB().queryBuilder();
clientQb.where().like("nomeRazao", "%" + pedido.getIdCliente().getNomeRazao() + "%");
return pedidoQb.join(clientQb).query();
}
required %%%%%%%% in LIKE! sorry all :)

Related

Spring Boot Data JPA сaused by: Error accessing field

community!
I get an error (Error accessing field) when in application.properties I change the value (spring.jpa.hibernate.ddl-auto) from create-drop to validate or update.
The error occurs when I try to get the OwnerProfile object from the database.
I use:
spring boot: 2.4.1
postgresql driver: 42.2.5
Caused by: org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.2.jar:5.3.2]
at com.sun.proxy.$Proxy98.findOwnerProfileByPk(Unknown Source) ~[na:na]
at com.gmail.andreyzarazka.giveawaystatistics.service.impl.OwnerProfileServiceImpl.info(OwnerProfileServiceImpl.java:50) ~[classes/:na]
at com.gmail.andreyzarazka.giveawaystatistics.GiveawayStatisticsApp.lambda$commandLineRunner$0(GiveawayStatisticsApp.java:44) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.1.jar:2.4.1]
... 10 common frames omitted
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:75) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue(AbstractComponentTuplizer.java:59) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.ComponentType.getPropertyValue(ComponentType.java:419) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.ComponentType.getHashCode(ComponentType.java:246) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.spi.EntityUniqueKey.generateHashCode(EntityUniqueKey.java:67) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.spi.EntityUniqueKey.<init>(EntityUniqueKey.java:48) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:748) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:467) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad$EntityResolver.lambda$static$0(TwoPhaseLoad.java:605) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntityEntryLoadedState(TwoPhaseLoad.java:248) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:182) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:151) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1200) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:1001) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:959) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2850) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2832) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2664) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.list(Loader.java:2659) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1414) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1625) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1593) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1641) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:111) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:406) ~[spring-orm-5.3.2.jar:5.3.2]
at com.sun.proxy.$Proxy115.getSingleResult(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:196) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:155) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.2.jar:5.3.2]
... 20 common frames omitted
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field giveawaystatistics.model.OwnerProfile.pk to java.lang.Long
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ~[na:na]
at java.base/java.lang.reflect.Field.get(Field.java:419) ~[na:na]
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
... 69 common frames omitted
My application.properties file looks like this
spring.datasource.url=jdbc:postgresql://localhost:5432/gsdb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true
#Entity(name = "OwnerProfile")
#Table(name = "owner_profile",
uniqueConstraints = {
#UniqueConstraint(
name = "owner_profile_pk_unique",
columnNames = "pk"),
#UniqueConstraint(
name = "owner_profile_username_unique",
columnNames = "username")})
public class OwnerProfile implements Serializable {
#Id
#SequenceGenerator(
name = "owner_profile_sequence",
sequenceName = "owner_profile_sequence",
allocationSize = 1)
#GeneratedValue(
strategy = SEQUENCE,
generator = "owner_profile_sequence")
#Column(
name = "id",
updatable = false)
private Long id;
#Column(
name = "pk",
nullable = false,
updatable = false)
private Long pk;
#Column(
name = "username",
nullable = false,
columnDefinition = "TEXT")
private String username;
#Column(
name = "profile_pic_url",
nullable = false,
columnDefinition = "TEXT")
private String profilePicUrl;
#Column(
name = "phone_number",
nullable = true,
columnDefinition = "TEXT")
private String phoneNumber;
#OneToOne(
mappedBy = "ownerProfile",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
private Company company;
public OwnerProfile() {
}
public OwnerProfile(SelfProfile profile) {
this.pk = profile.getPk();
this.username = profile.getUsername();
this.profilePicUrl = profile.getProfilePicUrl();
this.phoneNumber = profile.getPhoneNumber();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProfilePicUrl() {
return profilePicUrl;
}
public void setProfilePicUrl(String profilePicUrl) {
this.profilePicUrl = profilePicUrl;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Company)) return false;
Company company = (Company) o;
return getId().equals(company.getId())
&& getPk().equals(company.getPk())
&& getUsername().equals(company.getUsername());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getPk(), getUsername());
}
#Override
public String toString() {
return "OwnerProfileService{" +
"id=" + id +
", pk=" + pk +
", username='" + username + '\'' +
", profilePicUrl='" + profilePicUrl + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
#Entity(name = "Company")
#Table(
name = "company",
uniqueConstraints = {
#UniqueConstraint(
name = "company_pk_unique",
columnNames = "pk"),
#UniqueConstraint(
name = "company_username_unique",
columnNames = "username")})
public class Company implements Serializable {
#Id
#SequenceGenerator(
name = "company_sequence",
sequenceName = "company_sequence",
allocationSize = 1)
#GeneratedValue(
strategy = SEQUENCE,
generator = "company_sequence")
#Column(
name = "id",
updatable = false)
private Long id;
#Column(
name = "pk",
nullable = false,
updatable = false)
private Long pk;
#Column(
name = "username",
nullable = false,
columnDefinition = "TEXT")
private String username;
#Column(
name = "full_name",
nullable = true,
columnDefinition = "TEXT")
private String fullName;
#Column(
name = "profile_pic_url",
nullable = false,
columnDefinition = "TEXT")
private String profilePicUrl;
#Column(
name = "profile_pic_id",
nullable = true,
columnDefinition = "TEXT")
private String profilePicId;
#Column(
name = "following_count",
nullable = false)
private Integer followingCount;
#Column(
name = "biography",
nullable = true,
columnDefinition = "TEXT")
private String biography;
#Column(
name = "account_type",
nullable = false)
private Integer accountType;
#Column(
name = "is_private",
nullable = false,
columnDefinition = "boolean default false")
private Boolean isPrivate;
#Column(
name = "is_business",
nullable = false,
columnDefinition = "boolean default false")
private Boolean isBusiness;
#OneToOne(
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
#JoinColumn(
name = "owner_profile_pk",
referencedColumnName = "pk",
foreignKey = #ForeignKey(
name = "owner_profile_pk_fk"))
private OwnerProfile ownerProfile;
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL)
private Set<CompanyRegistration> companyRegistrations = new HashSet<>();
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL)
private Set<GiveawayFollowers> giveawayFollowers = new HashSet<>();
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
private Set<TargetAudience> targetAudiences = new HashSet<>();
public Company() {
}
public Company(User user) {
this.pk = user.getPk();
this.username = user.getUsername();
this.fullName = user.getFull_name();
this.profilePicUrl = user.getProfile_pic_url();
this.profilePicId = user.getProfile_pic_id();
this.followingCount = user.getFollowing_count();
this.biography = user.getBiography();
this.accountType = user.getAccount_type();
this.isPrivate = user.is_private();
this.isBusiness = user.is_business();
}
public Company(Long pk,
String username,
String fullName,
String profilePicUrl,
String profilePicId,
Integer followingCount,
String biography,
Integer accountType,
Boolean isPrivate,
Boolean isBusiness) {
this.pk = pk;
this.username = username;
this.fullName = fullName;
this.profilePicUrl = profilePicUrl;
this.profilePicId = profilePicId;
this.followingCount = followingCount;
this.biography = biography;
this.accountType = accountType;
this.isPrivate = isPrivate;
this.isBusiness = isBusiness;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getProfilePicUrl() {
return profilePicUrl;
}
public void setProfilePicUrl(String profilePicUrl) {
this.profilePicUrl = profilePicUrl;
}
public String getProfilePicId() {
return profilePicId;
}
public void setProfilePicId(String profilePicId) {
this.profilePicId = profilePicId;
}
public Integer getFollowingCount() {
return followingCount;
}
public void setFollowingCount(Integer followingCount) {
this.followingCount = followingCount;
}
public String getBiography() {
return biography;
}
public void setBiography(String biography) {
this.biography = biography;
}
public Integer getAccountType() {
return accountType;
}
public void setAccountType(Integer accountType) {
this.accountType = accountType;
}
public Boolean getPrivate() {
return isPrivate;
}
public void setPrivate(Boolean aPrivate) {
isPrivate = aPrivate;
}
public Boolean getBusiness() {
return isBusiness;
}
public void setBusiness(Boolean business) {
isBusiness = business;
}
public OwnerProfile getOwnerProfile() {
return ownerProfile;
}
public void setOwnerProfile(OwnerProfile ownerProfile) {
this.ownerProfile = ownerProfile;
}
public Set<CompanyRegistration> getCompanyRegistrations() {
return companyRegistrations;
}
public void addCompanyRegistration(CompanyRegistration companyRegistration) {
companyRegistrations.add(companyRegistration);
}
public void removeCompanyRegistration(CompanyRegistration companyRegistration) {
companyRegistrations.remove(companyRegistration);
}
public Set<GiveawayFollowers> getGiveawayFollowers() {
return giveawayFollowers;
}
public void addGiveawayFollower(GiveawayFollowers giveawayFollowers) {
this.giveawayFollowers.add(giveawayFollowers);
}
public void removeGiveawayFollower(GiveawayFollowers giveawayFollowers) {
this.giveawayFollowers.remove(giveawayFollowers);
}
public Set<TargetAudience> getTargetAudiences() {
return targetAudiences;
}
public void addTargetAudience(TargetAudience targetAudience) {
this.targetAudiences.add(targetAudience);
}
public void removeTargetAudience(TargetAudience targetAudience) {
this.targetAudiences.remove(targetAudience);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Company)) return false;
Company company = (Company) o;
return getId().equals(company.getId())
&& getPk().equals(company.getPk())
&& getUsername().equals(company.getUsername());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getPk(), getUsername());
}
#Override
public String toString() {
return "CompanyDetails{" +
"id=" + id +
", pk=" + pk +
", username='" + username + '\'' +
", fullName='" + fullName + '\'' +
", profilePicUrl='" + profilePicUrl + '\'' +
", profilePicId=" + profilePicId +
", followingCount=" + followingCount +
", biography='" + biography + '\'' +
", accountType=" + accountType +
", isPrivate=" + isPrivate +
", isBusiness=" + isBusiness +
'}';
}
}
public interface OwnerProfileRepository extends JpaRepository<OwnerProfile, Long> {
Optional<OwnerProfile> findOwnerProfileByPk(Long pk);
}
Any idea why this is happening and how you can fix it?

A CallableStatement function was executed and the out parameter 1 was of type java.sql.Types=2001 however type java.sql.Types=1111 was registered

I am trying to call a STORED PROCEDURE(with a out refcursor parameter) in postgresql through JPA2.1 like this:
public class JpaINParam {
public static void main(String[] args) throws Exception {
EntityManagerFactory emfactory = Persistence
.createEntityManagerFactory("JPA2");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
StoredProcedureQuery q = entitymanager.createNamedStoredProcedureQuery("get_hibernate_dtl");
q.setParameter("modeval", "1");
q.execute();
#SuppressWarnings("unchecked")
List<Student> students = (List<Student>) q.getOutputParameterValue("resultset");
for (Student student : students) {
System.out.println(student.getFname());
}
entitymanager.getTransaction().commit();
entitymanager.close();
try {
// storedProcedure.executeUpdate();
System.out.println("444444444444");
} catch (Exception e) {
e.printStackTrace();
}
}
}
i get the following error:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: A CallableStatement function was executed and the out parameter 1 was of
type java.sql.Types=2001 however type java.sql.Types=1111 was
registered.
Error Code: 0
Call: {?= CALL get_hibernate_dtl(?)}
bind => [2 parameters bound]
Query: ResultSetMappingQuery(name="get_hibernate_dtl" )
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:378)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.StoredProcedureQueryImpl.execute(StoredProcedureQueryImpl.java:316)
at com.javacodegeeks.examples.jpa.service.JpaINParam.main(JpaINParam.java:36)
the following is my entity class:
#NamedStoredProcedureQuery(name="get_hibernate_dtl", procedureName="get_hibernate_dtl", resultClasses={Student.class}, returnsResultSet = true, parameters={
#StoredProcedureParameter(queryParameter="resultset", name="resultset", mode=ParameterMode.REF_CURSOR,type=Class.class),
#StoredProcedureParameter(queryParameter="modeval", name="modeval", mode=ParameterMode.IN,type=String.class)
})
#Entity
public class Student {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private int sid;
private String fname;
private String lname;
private String dept;
private int year;
private String email;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(int sid, String fname, String lname, String dept, int year,
String email) {
super();
this.sid = sid;
this.fname = fname;
this.lname = lname;
this.dept = dept;
this.year = year;
this.email = email;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [sid=" + sid + ", fname=" + fname + ", lname=" + lname
+ ", dept=" + dept + ", year=" + year + ", email=" + email
+ "]";
}
}
this is my procedure in postgresql:
CREATE OR REPLACE PROCEDURE dwh.get_hibernate_dtl(resultset OUT ahis_type.refcursor, modeval IN character varying DEFAULT '1'::character varying) AS
query VARCHAR2 (6000);
v_type NUMERIC(3,0);
v_dwh_type_id VARCHAR2(100);
BEGIN
IF (modeval = 1) THEN
QUERY := ' SELECT sid,fname FROM STUDENT ';
END IF;
INSERT INTO tmp_table values ( 'get_hibernate_dtl----Modeval-->'||modeval||'query--->'||QUERY );
OPEN resultset FOR QUERY;
END

NullPointerException is occurring with createNamedQuery and then persistence unit logins successfully

I can't seem to solve this issue. I have tried googling but can't put the pieces together to solve it. I have the following stack trace:
Warning: java.lang.NullPointerException
at org.eclipse.persistence.platform.server.ServerPlatformUtils.createServerPlatform(ServerPlatformUtils.java:99)
at org.eclipse.persistence.sessions.factories.SessionManager.init(SessionManager.java:77)
at org.eclipse.persistence.sessions.factories.SessionManager.<clinit>(SessionManager.java:71)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.addSessionToGlobalSessionManager(EntityManagerSetupImpl.java:907)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.initSession(EntityManagerSetupImpl.java:2671)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:675)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:305)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:337)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:318)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:521)
at session.CategoryFacade.findRandom(CategoryFacade.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy173.findRandom(Unknown Source)
at session.__EJB31_Generated__CategoryFacade__Intf____Bean__.findRandom(Unknown Source)
at actions.ActionFacade.setFeaturedCategories(ActionFacade.java:82)
at actions.HomeAction.execute(HomeAction.java:16)
at controller.ControllerServlet.service(ControllerServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Info: EclipseLink, version: Eclipse Persistence Services - 2.6.1.v20150605-31e8258
Info: /file:/Users/csexton/NetBeansProjects/ReadersParadise/build/web/WEB-INF/classes/_AffableBeanPU login successful
So if you look at the last two lines my persistent unit isn't logging in until I try to use the entity manager. If I do another query after the first one, everything is good, no errors, nothing......Error occurs on the createNamedQuery. The query exists and matches the exact name. I can call the same method twice and the first one causes a NPE but the second one works fine.
#Stateless(name="CategoryFacade")
public class CategoryFacade extends AbstractFacade<Category> {
#PersistenceContext(unitName = "AffableBeanPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CategoryFacade() {
super(Category.class);
}
public List<Category> findRandom(int limit) {
return getEntityManager()
.createNamedQuery("Category.findRandomByLimit")
.setParameter(1, limit)
.getResultList();
}
}
I am doing a jndi lookup for the class
public class ActionFacade implements AutoCloseable {
private static ThreadLocal<ActionFacade> instance = new ThreadLocal<>();
private HttpServletRequest request;
private HttpSession session;
private CategoryFacade categoryFacade;
private BookFacade bookFacade;
private OrderManager orderManager;
private ShoppingCart cart;
public ActionFacade(HttpServletRequest request) {
this.request = request;
this.session = request.getSession();
try {
Context ctx = new InitialContext();
this.categoryFacade = (CategoryFacade) ctx.lookup(
"java:global/ReadersParadise/CategoryFacade!session.CategoryFacade");
System.out.print("JNDI lookup complete.");
this.bookFacade = (BookFacade) ctx.lookup(
"java:global/ReadersParadise/BookFacade!session.BookFacade");
this.orderManager = (OrderManager) ctx.lookup(
"java:global/ReadersParadise/OrderManager!session.OrderManager");
} catch (NamingException ex) {
System.err.println(ex);
}
}
public static ActionFacade create(HttpServletRequest request) {
ActionFacade facade = new ActionFacade(request);
instance.set(facade);
return facade;
}
public static ActionFacade getCurrentInstance() {
return instance.get();
}
#Override
public void close() {
instance.remove();
}
public void setSelectedCategory() {
String categoryName = request.getParameter("category");
Category selectedCategory = categoryFacade.findByName(categoryName);
if (selectedCategory == null) {
selectedCategory = categoryFacade.find(1);
}
session.setAttribute("selectedCategory", selectedCategory);
Collection<Book> categoryBooks = selectedCategory.getBookCollection();
session.setAttribute("categoryBooks", categoryBooks);
}
public void setAllCategories() {
request.setAttribute("categories", categoryFacade.findAll());
}
}
Then in my servlet I am using the ActionFacade like this....
try(ActionFacade facade = ActionFacade.create(request)) {
Action action = ActionFactory.getAction(request);
String view = action.execute(facade);
System.out.println(request.getServletPath());
if (request.getServletPath().equals("") || view.equals(request.getServletPath().substring(1))) {
request.getRequestDispatcher("/WEB-INF/views/" + view + ".jsp").forward(request, response);
} else {
response.sendRedirect(view);
}
} catch (NullPointerException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
throw new ServletException("Executing action failed.", e);
}
This is the category entity
#Entity
#Table(name = "category")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name= :name")
})
#NamedNativeQuery(name = "Category.findRandomByLimit",
query = "SELECT * FROM Category ORDER BY RAND() LIMIT ?1")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Collection<Book> bookCollection;
public Category() {
}
public Category(Integer id) {
this.id = id;
}
public Category(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Category)) {
return false;
}
Category other = (Category) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Category[ id=" + id + " ]";
}
}
Category Action Class which uses the ActionFacade
public class CategoryAction implements Action {
#Override
public String execute(ActionFacade facade) throws Exception {
facade.setSelectedCategory();
facade.setAllCategories();
return "category";
}
}
I think it is a problem of Glassfish 4.1.1 described here:
https://java.net/jira/browse/GLASSFISH-21468
According this, it may help, if you add
<property name="eclipselink.target-server" value="Glassfish"/>
to your persistence.xml

ClassCastException on itself after redeploy of same application`

I am developing a JSF application with Netbeans and Glassfish. When I change something and Netbeans redeploys to Glassfish, then a ClassCastException is been thrown on the entity class itself.
Caused by: java.lang.ClassCastException: com.twibu.entity.Tipper cannot be cast to com.twibu.entity.Tipper
at com.twibu.service.TipperService.findByUseridPwd(TipperService.java:22)
How is this caused and how can I solve it?
For reference, here's the full stack trace:
WARNING: EJB5184:A system exception occurred during an invocation on EJB TipperService, method: public com.twibu.entity.Tipper com.twibu.service.TipperService.findByUseridPwd(java.lang.String,java.lang.String)
WARNING: javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
at com.sun.proxy.$Proxy141.findByUseridPwd(Unknown Source)
at com.twibu.service.__EJB31_Generated__TipperService__Intf____Bean__.findByUseridPwd(Unknown Source)
at com.twibu.bean.AuthBean.login(AuthBean.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassCastException: com.twibu.entity.Tipper cannot be cast to com.twibu.entity.Tipper
at com.twibu.service.TipperService.findByUseridPwd(TipperService.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
... 44 more
Here's the entity:
#Entity
#Table(name = "tipper")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Tipper.findAll", query = "SELECT t FROM Tipper t"),
#NamedQuery(name = "Tipper.findById", query = "SELECT t FROM Tipper t WHERE t.id = :id"),
#NamedQuery(name = "Tipper.findByName", query = "SELECT t FROM Tipper t WHERE t.name = :name"),
#NamedQuery(name = "Tipper.findByUserid", query = "SELECT t FROM Tipper t WHERE t.userid = :userid"),
#NamedQuery(name = "Tipper.findByPwd", query = "SELECT t FROM Tipper t WHERE t.pwd = :pwd"),
#NamedQuery(name = "Tipper.findByEmail", query = "SELECT t FROM Tipper t WHERE t.email = :email")})
#NamedNativeQueries({
#NamedNativeQuery(name = "Tipper.findByUseridPwd", query = "" +
"SELECT a.id AS id, " +
" a.idgruppe AS idgruppe, " +
" a.name AS name, " +
" a.userid AS userid, " +
" a.pwd AS pwd, " +
" a.email AS email " +
"FROM tipper AS a " +
"WHERE a.userid = ? " +
" AND a.pwd = MD5(?)",
resultClass=Tipper.class)})
public class Tipper implements Serializable {
private static final long serialVersionUID = 20130311L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "userid")
private String userid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 32)
#Column(name = "pwd")
private String pwd;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "email")
private String email;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "tipper")
private Collection<Zulassung> zulassungCollection;
#JoinColumn(name = "idgruppe", referencedColumnName = "id")
#ManyToOne(optional = false)
private Gruppe idgruppe;
public Tipper() {
}
public Tipper(Integer id) {
this.id = id;
}
public Tipper(Integer id, String name, String userid, String pwd, String email) {
this.id = id;
this.name = name;
this.userid = userid;
this.pwd = pwd;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlTransient
public Collection<Zulassung> getZulassungCollection() {
return zulassungCollection;
}
public void setZulassungCollection(Collection<Zulassung> zulassungCollection) {
this.zulassungCollection = zulassungCollection;
}
public Gruppe getIdgruppe() {
return idgruppe;
}
public void setIdgruppe(Gruppe idgruppe) {
this.idgruppe = idgruppe;
}
public boolean isUser() {
return idgruppe.getName().equals("user") || idgruppe.getName().equals("admin");
}
public boolean isAdmin() {
return idgruppe.getName().equals("admin");
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Tipper)) {
return false;
}
Tipper other = (Tipper) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.twibu.entity.Tipper[ id=" + id + " ]";
}
}
And here's the service class:
#Singleton
public class TipperService extends AbstractService {
public Tipper findByUseridPwd(String userid, String pwd) {
Query nq = getTwibuManager().createNamedQuery("Tipper.findByUseridPwd");
nq.setParameter(1, userid);
nq.setParameter(2, pwd);
return (Tipper)nq.getSingleResult();
}
}
Seems like the old application is not getting undeployed.
If you are not using a container managed persistence unit, then you need to close your EntityManagerFactory when undeploying.

EclipseLink GeneratedValue null on postgres only on one entity

I have a rather weird case. I have some entities generated with netbeans and i can persist all except one. I see no difference in the database nor in the entity class. Can someone help me, here is my entity class , database, and error that i am receiving
CREATE TABLE objekat
(
id_objekat bigserial NOT NULL,
id_opstina serial NOT NULL,
naziv character varying(50) NOT NULL,
kapacitet character varying(50),
adresa character varying(100),
lokacija_sirina double precision,
lokacija_duzina double precision,
opis character varying(500),
korisnicko_ime character varying(50),
sifra character varying(50),
maks_broj_slike integer,
absolute_path_logo character varying(255),
CONSTRAINT objekat_pkey PRIMARY KEY (id_objekat),
CONSTRAINT fkobjekat924176 FOREIGN KEY (id_opstina)
REFERENCES opstina (id_opstina) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
and this is my entity bean.
#Entity
#Table(name = "objekat")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Objekat.findAll", query = "SELECT o FROM Objekat o"),
#NamedQuery(name = "Objekat.findByIdObjekat", query = "SELECT o FROM Objekat o WHERE o.idObjekat = :idObjekat"),
#NamedQuery(name = "Objekat.findByNaziv", query = "SELECT o FROM Objekat o WHERE upper (o.naziv) like upper(:naziv)"),
#NamedQuery(name = "Objekat.findByNazivAndOpstina", query = "SELECT o FROM Objekat o inner join o.idOpstina op WHERE upper (o.naziv) like upper(:naziv) and op.idOpstina = :idOpstina"),
#NamedQuery(name = "Objekat.findByKapacitet", query = "SELECT o FROM Objekat o WHERE o.kapacitet = :kapacitet"),
#NamedQuery(name = "Objekat.findByAdresa", query = "SELECT o FROM Objekat o WHERE o.adresa = :adresa"),
#NamedQuery(name = "Objekat.findByLokacijaSirina", query = "SELECT o FROM Objekat o WHERE o.lokacijaSirina = :lokacijaSirina"),
#NamedQuery(name = "Objekat.findByLokacijaDuzina", query = "SELECT o FROM Objekat o WHERE o.lokacijaDuzina = :lokacijaDuzina")})
public class Objekat implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_objekat",columnDefinition = "BIGSERIAL")
private Long idObjekat;
#Size(max = 255)
#Column(name = "absolute_path_logo")
private String absolutePathLogo;
#OneToMany( mappedBy = "objekatidObjekat")
private List<DogadjajObjekat> dogadjajObjekatList;
#OneToMany( mappedBy = "objekatidObjekat")
private List<SlikeLokacijaObjekat> slikeLokacijaObjekatList;
#OneToMany( mappedBy = "idObjekat")
private List<RasporedObjekat> rasporedObjekatList;
#Column(name = "maks_broj_slike")
private Integer maksBrojSlike;
#Size(max = 50)
#Column(name = "korisnicko_ime")
private String korisnickoIme;
#Size(max = 50)
#Column(name = "sifra")
private String sifra;
#Size(max = 500)
#Column(name = "opis")
private String opis;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "lokacija_sirina")
private Double lokacijaSirina;
#Column(name = "lokacija_duzina")
private Double lokacijaDuzina;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "naziv")
private String naziv;
#Size(max = 50)
#Column(name = "kapacitet")
private String kapacitet;
#Size(max = 100)
#Column(name = "adresa")
private String adresa;
#JoinTable(name = "tip_objekta_objekat", joinColumns = {
#JoinColumn(name = "objekatid_objekat", referencedColumnName = "id_objekat")}, inverseJoinColumns = {
#JoinColumn(name = "tip_objektaid_tip_objekta", referencedColumnName = "id_tip_objekta")})
#ManyToMany
private List<TipObjekta> tipObjektaList;
#JoinColumn(name = "id_opstina", referencedColumnName = "id_opstina")
#ManyToOne(optional = false)
private Opstina idOpstina;
public Objekat() {
}
public Objekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public Objekat(Long idObjekat, String naziv) {
this.idObjekat = idObjekat;
this.naziv = naziv;
}
public Long getIdObjekat() {
return idObjekat;
}
public void setIdObjekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public String getKapacitet() {
return kapacitet;
}
public void setKapacitet(String kapacitet) {
this.kapacitet = kapacitet;
}
public String getAdresa() {
return adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
#XmlTransient
public List<TipObjekta> getTipObjektaList() {
return tipObjektaList;
}
public void setTipObjektaList(List<TipObjekta> tipObjektaList) {
this.tipObjektaList = tipObjektaList;
}
public Opstina getIdOpstina() {
return idOpstina;
}
public void setIdOpstina(Opstina idOpstina) {
this.idOpstina = idOpstina;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idObjekat != null ? idObjekat.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 Objekat)) {
return false;
}
Objekat other = (Objekat) object;
if ((this.idObjekat == null && other.idObjekat != null) || (this.idObjekat != null && !this.idObjekat.equals(other.idObjekat))) {
return false;
}
return true;
}
#Override
public String toString() {
return "rs.dzetSet.entiteti.Objekat[ idObjekat=" + idObjekat + " ]";
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
public Double getLokacijaSirina() {
return lokacijaSirina;
}
public void setLokacijaSirina(Double lokacijaSirina) {
this.lokacijaSirina = lokacijaSirina;
}
public Double getLokacijaDuzina() {
return lokacijaDuzina;
}
public void setLokacijaDuzina(Double lokacijaDuzina) {
this.lokacijaDuzina = lokacijaDuzina;
}
public String getKorisnickoIme() {
return korisnickoIme;
}
public void setKorisnickoIme(String korisnickoIme) {
this.korisnickoIme = korisnickoIme;
}
public String getSifra() {
return sifra;
}
public void setSifra(String sifra) {
this.sifra = sifra;
}
public Integer getMaksBrojSlike() {
return maksBrojSlike;
}
public void setMaksBrojSlike(Integer maksBrojSlike) {
this.maksBrojSlike = maksBrojSlike;
}
public void pocevajMaksBrojSlike(){
this.maksBrojSlike++;
}
public String getAbsolutePathLogo() {
return absolutePathLogo;
}
public void setAbsolutePathLogo(String absolutePathLogo) {
this.absolutePathLogo = absolutePathLogo;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPrePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(!ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPoslePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<DogadjajObjekat> getDogadjajObjekatList() {
return dogadjajObjekatList;
}
public void setDogadjajObjekatList(List<DogadjajObjekat> dogadjajObjekatList) {
this.dogadjajObjekatList = dogadjajObjekatList;
}
#XmlTransient
public List<SlikeLokacijaObjekat> getSlikeLokacijaObjekatList() {
return slikeLokacijaObjekatList;
}
public void setSlikeLokacijaObjekatList(List<SlikeLokacijaObjekat> slikeLokacijaObjekatList) {
this.slikeLokacijaObjekatList = slikeLokacijaObjekatList;
}
#XmlTransient
public List<RasporedObjekat> getRasporedObjekatList() {
return rasporedObjekatList;
}
public void setRasporedObjekatList(List<RasporedObjekat> rasporedObjekatList) {
this.rasporedObjekatList = rasporedObjekatList;
}
and i persist it in a rather normal way, or i just think so.
utx.begin();
if(noviObjekat.getIdObjekat() == null){
em.persist(noviObjekat);
}else{
em.merge(noviObjekat);
}
utx.commit();
and i get a pretty weird error
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: null value in column "id_opstina" violates not-null constraint
Error Code: 0
Call: INSERT INTO objekat (absolute_path_logo, adresa, kapacitet, korisnicko_ime, lokacija_duzina, lokacija_sirina, maks_broj_slike, naziv, opis, sifra, id_opstina) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(rs.dzetSet.entiteti.Objekat[ idObjekat=null ])
}
You set a generator on the field for "id_objekat" but the exception is for the not-null constraint on "id_opstina". You will need to set this field yourself or use a returning policy to get it instead:
http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#Using_EclipseLink_JPA_Extensions_for_Returning_Policy